Expresso 5-6

com.jcorporate.expresso.core.dbobj
Class DBObject

java.lang.Object
  extended bycom.jcorporate.expresso.core.dataobjects.BaseDataObject
      extended bycom.jcorporate.expresso.core.dataobjects.jdbc.JDBCDataObject
          extended bycom.jcorporate.expresso.core.dbobj.DBObject
All Implemented Interfaces:
Cacheable, ContextNested, DataObject, LookupInterface, Serializable
Direct Known Subclasses:
ChangeLog, RowGroupPerms, RowPermissions, SecuredDBObject

public abstract class DBObject
extends JDBCDataObject
implements Cacheable, LookupInterface

DBObjects are the core of Expresso's object-relational mapping. They are object-oriented wrappers for some sort of data. They are generally expected to be used in a single thread, like in processing a web query.

When making your own application, you derive your classes from DBObject or SecuredDBObject.

Since:
Expresso 1.0
Author:
Michael Nash
See Also:
SecuredDBObject, DBException, DBConnection, Serialized Form

Nested Class Summary
 class DBObject.FieldError
          Private class that defines errors for fields.
 class DBObject.FieldUpdate
          Private class used to track field updates
 
Field Summary
static String ATTRIBUTE_ERROR
          Attribute String for if there's an error with the field.
static String ATTRIBUTE_ERROR_MESSAGE
          Attribute String for what message to display if there's an error with thie field.
static String ATTRIBUTE_PAGE_LIMIT
          Attribute for what is the limit to retrieve from searchAndRetrieve operations
protected static BigDecimal BIG_DECIMAL_ZERO
          A static zero BIG DECIMAL object

author Peter Pilgrim

static String EMAIL_MASK
          Email Regular Expression Constant.
static String EVENT_ADD
          Event 'Add' code
static String EVENT_DELETE
          Event 'Delete' Code
static String EVENT_UPDATE
          Event 'Update' Code
static String FLOAT_MASK
          Floating point regular expression syntax for easy reference.
static String INT_MASK
          Integer Regular Expression for easy reference
static String IS_CHECK_RELATIONAL_INTEGRITY
           
static String UPDATE_CHANGED_ONLY
          setup code for update() policy: for efficiency, developers who are confident that their code does not have any 'blind updates' can set the Setup value UPDATE_CHANGED_ONLY to true (a blind update is where the object is not retieved before values in it are reset)
static String WHERE_KEYWORD
           
 
Fields inherited from class com.jcorporate.expresso.core.dataobjects.jdbc.JDBCDataObject
anyFieldsDistinct, anyFieldsToRetrieve, appendCustomWhere, caseSensitiveQuery, customWhereClause, dbKey, distinctFields, localConnection, LONGBINARY_READ_DEFAULT_SIZE, maxRecords, myClassName, myUpdates, offsetRecord, recordSet, retrieveFields, sMetadataMap, sortKeys
 
Fields inherited from class com.jcorporate.expresso.core.dataobjects.BaseDataObject
currentStatus, globalMask
 
Fields inherited from interface com.jcorporate.expresso.core.dataobjects.DataObject
STATUS_CURRENT, STATUS_DELETED, STATUS_NEW, STATUS_UPDATED
 
Constructor Summary
DBObject()
          Default Constructor.
DBObject(DBConnection newConnection)
          Constructor that sets a connection as the object is created - typically this is used when a particular DBConnection is required for the purposes of maintaining a database transaction.
DBObject(DBConnection newConnection, String setupTablesContext)
          Constructor that sets a connection as the object is created - typically this is used when a particular DBConnection is required for the purposes of maintaining a database transaction.
DBObject(RequestContext request)
          For using DBObjects within Controllers.
DBObject(String newdbKey)
          Initialize this DBObject and set the db/context to the specified key
 
Method Summary
 void add()
          Add a new record to the target table.
protected  void addDetail(String objName, String keyFieldsLocal, String keyFieldsForeign)
          Specify a new "detail" db object, and the fields in this object they specify the fields in the related object
protected  void addField(String fieldName, String fieldType, int fieldSize, boolean allowNull, String fieldDescription)
          Add a field with more details: This version of addfield supplies the allowNull flags and a description of the field to be used when reporting errors to the user.
protected  void addField(String fieldName, String fieldType, int fieldSize, int fieldPrecision, boolean allowNull, String fieldDescription)
          Add a field with more details: This version allows the user to specify a precision, for fields that use both a size and precision.
protected  void addFieldError(String fieldName, String errorMessage)
          Use this in your derived checkField() class to add error messages to be associated with various fields.
 void addFoundKeys(String fieldName)
          This is used internally by JDBC Exceutor's and JDBC Query when dealing with queries to the underlying datasource.
 void addIfNeeded()
          Determine if a record with this key exists already - if not, add a new record.
protected  void addIndex(String indexName, String fieldNames, boolean isUnique)
          Add an index to the table.
protected  void addKey(String keyFieldName)
          Add a new field to the list of fields that are part of this object's key.
 void addOrUpdate()
          Determine if a record with these fields exists already - if so, update.
 void addSortKey(String fieldString, boolean ascending)
          Add a field to be sorted in a search
protected  void addTransition(Transition t)
          ?????
protected  void addVirtualField(String fieldName, String fieldType, int fieldSize, int fieldPrecision, boolean allowNull, String fieldDescription)
          Add a field with more details: This version allows the user to specify a precision, for fields that use both a size and precision.
protected  void addVirtualField(String fieldName, String fieldType, int fieldSize, int fieldPrecision, boolean allowNull, String descripKey, String fieldDescription)
          Add a field with more details: This version allows the user to specify a precision, for fields that use both a size and precision.
protected  void addVirtualField(String fieldName, String fieldType, int fieldSize, String fieldDescription)
          Add a new virtual field to the definition of this object.
protected  void addVirtualField(String fieldName, String fieldType, int fieldSize, String descripKey, String fieldDescription)
          Add a new virtual field to the definition of this object.
 double average(String fieldName)
          Find the average of the values in the specified field of records selected by the DBObject selection criteria.
 void basicAdd()
          

A "simplified"e; version of add that can be used to do a basic INSERT statement into this table.

 void cacheIsChangedComparison()
          reset 'original' value and isChanged flags on all fields, establishing a baseline for comparison.
 boolean checkAllowed(String function)
          No security is applied at the DBObject level, only at the level of SecuredDBObjects.
protected  void checkAllReferredToBy()
          Extended by subclasses to make calls to ReferredToBy as needed.
protected  void checkAllRefs()
          Extended by subclasses to make calls to checkRef as needed.
 void checkAllRefsPublic()
          Public interface to checkAllRefs()
protected  void checkDeleteDetailPerm(DBObject obj)
          extracted for subclasses checking
 void checkField(String fieldName, String fieldValue)
          Check that a given value is valid for a given field.
protected  void checkRef(String foreignKeyNames, DBObject refObject, String errorMessage)
          Convenience method for checking a reference where blank is *not* allowed in the foreign key; This test can be turned off if you add an Expresso setup (configuration) entry, 'isCheckRelationalIntegrity' set to false
protected  void checkRef(String foreignKeyNames, DBObject refObject, String errorMessage, boolean allowBlank)
          Verify referential integrity from the given list of fields to the key fields in the given DB Object.
 void clear()
          Set all fields to empty value & clear the last result set & clear sort keys and customWhereClause
 void clearDistinctFields()
          This convenience method clears all the distinct flags of DBFields belonging to this DBObject

author Peter Pilgrim

protected  void clearError(String fieldName)
          Used to clear field error flags.
 void clearFieldsToRetrieve()
          This convenience method clears all the fileds to be retrieved DBFields belonging to this DBObject

author Yves Henri Amaizo

 void clearSortKeys()
          Clear the sort keys
protected  boolean containsWildCards(String fieldValue)
          See if this field value contains wild cards (e.g. pattern matching criteria for the database).
protected  void copyAttributes(DBObject returnObj)
          called by newInstance(), this method should make sure that the newly created object is properly initialized
 int count()
          Just like find, but only retrieves the count, not the records themselves.
 void delete()
          Delete this record from the target table.
 void delete(boolean deleteDetails)
          Delete this record, optionally deleting any associated detail records.
 void deleteAll()
          Delete all of the records specified by the current search criteria.
 void deleteAll(boolean oneByOne)
          Delete all of the records specified by the current search criteria.
protected  void deleteDetails(DBConnection detailConnection)
          If this DB object has associated detail objects, locate the appropriate related detail records and delete them as well.
protected  String denotesRange(String fieldValue)
          Does a given field value denote a range?
 boolean equals(Object parm1)
          Equals implementation.
 boolean find()
          A lot like retrieve, but works with any fields, not just the key field.
 String forKey()
          Return a string we can use in error messages to indicate the record that had the problem by including the key and the current database/context
 String formatDateTime(String fieldName)
          Given the value of a date/time or date/time field, return the value formatted as appropriate for the current DBMS.
 Object get(String fieldName)
          Directly gets the DataField Data without having to deal with the DataField itself
 Map getAllAttributes()
          Returns a Read Only Map containing all the current attributes set for this particular data object instance.
 Object getAttribute(String attribName)
          Return an "attribute".
 Iterator getAttributesIterator(String fieldName)
          Get an iterator for all of the attributes specified for a field
protected  String getBooleanFieldValue(boolean fieldValue)
          Internal refactoring for getting what a boolean field should be set to.
 int getCacheSize()
          Gets the set size of the cache for this DBOBject
static HashMap getCacheStatsMap()
           
protected  CacheUtils getCacheUtil()
          'Pseudo' factory method to retrieve the caching utility class instance.
 boolean getCheckZeroUpdate()
          Gets the check zero update flags for this DBObject.
 String getCustomWhereClause()
          Allows us to query the custom where clause (if any). ' WHERE ' has been prepended to the clause.
 String getDataContext()
          Returns the name of the currently set DataContext
 DataField getDataField(String fieldName)
          Same as getField, but works with the DataObject interface for now.
 DataTransferObject getDataTransferObject()
          Gets the data transfer object usually for serialization purposes
 String getDBName()
          Deprecated. since Expresso 5.1 Use getDataContext() instead
 Enumeration getDetails()
          Get a list of all db objects that are specified as being "details" to this db object.
 int getDistinctFieldCount()
          This convenience method counts DBFields belonging to this DBObject that are set to distinct.
 String[] getDistinctFields()
          This convenience method iterates through all the fields belonging to this DBObject returns an array of field names ( String ) that are set to distinct.
 String getField(String fieldName)
          Get the string value of a field in this object as a string
 BigDecimal getFieldBigDecimal(String fieldName)
          Get the BigDecimal value of a field in this object.
 boolean getFieldBoolean(String fieldName)
          Boolean typesafe getField
 byte getFieldByte(String fieldName)
          Get the primitive byte value of a field in this object.
 byte[] getFieldByteArray(String fieldName)
          Get the primitive byteArray value of a field in this object.
protected  String getFieldData(String fieldName)
          Internal mechanism for getting the raw field data
 Date getFieldDate(String fieldName)
          Return the value of a field as a Date object
 String getFieldDecimalFormatted(String fieldName, String formatPattern)
          Return the value of a field as a Date object
 double getFieldDouble(String fieldName)
          Get the primitive double value of a field in this object. we use the locale specified in the properties file directly to determine how to parse the field
 String getFieldErrorMessage(String fieldName)
          Retrieve the error message associated with this field.
 float getFieldFloat(String fieldName)
          Get the primitive float value of a field in this object. we use the locale specified in the properties file directly to determine how to parse the field
 int getFieldInt(String fieldName)
          Get the primitive integer value of a field in this object.
 long getFieldLong(String fieldName)
          Get the prmitive long value of a field in this object.
 DataFieldMetaData getFieldMetaData(String fieldName)
          Returns the metadata for the specified field.
 short getFieldShort(String fieldName)
          Get the primitive integer value of a field in this object.
 int getFieldsToRetrieveCount()
          This convenience method counts DBFields belonging to this DBObject that are set to retrieve.
 Class getFilterClass()
          the INSTANCE value of filter class that will be used for all string filtering for THIS INSTANCE.
 long getFoundCount()
          Return the number of records found in the last search operation.
 Object[] getFoundKeysArray()
          Return the Array of keys (in the form field/field/field) that was found in the last search() call
 Object[] getIndexArray()
          Deprecated. since 5.6, Use ((DBObjectDef)getMetaData()).getIndexArray() instead
protected  Vector getISOValuesDefault(String valueField, String descripField)
          Basic version of getValidValues with supports internationalisation (i18n) that stores/retrieves the valid values in a locale dependent Caches

Valid values are store inside cache with a key name that equals myClassName+"."

protected  Vector getISOValuesDefault(String valueField, String descripField, String whereClause)
          Basic filtered version of getValidValues with supports internationalisation (i18n) that stores/retrieves the valid values in a locale dependent Caches

Valid values are store inside cache with a key name that equals myClassName+"."

protected  Vector getISOValuesDefault(String valueField, String descripField, String whereClause, String sortKeyString)
          Basic version of getValidValues with supports internationalisation (i18n) that stores/retrieves the valid values in a locale dependent Caches.
 String getKey()
          Get a string consisting of the values of each key field for this object appended together with a | between them.
 Iterator getKeyFieldListIterator()
          Get a list of all of the fields in this object This iterator is not thread safe.
 String getLength(String fieldName)
          Return the length of a field
 int getLengthInt(String fieldName)
          Get the length of this field as an integer
 DBConnection getLocalConnection()
          Returns the local connection currently associated with this DBObject...
 Locale getLocale()
          Get the current locale for this dbobject
 org.apache.log4j.Logger getLogger()
          convenience for getting logger for current (sub) class
 String getLookupObject(String fieldName)
          Get a field's lookup object - this is the name of another database object that can be used to look up valid values for this object.
 String getMax(String fieldName)
          Get the Maximum value in the table of a particular field

Contributed by Madan Mohanrao Kulkarni [kulsmadya@rediffmail.com]

 String getMax(String fieldName, boolean whereClause)
          Get the Maximum value in the table of a particular field

Contributed by Madan Mohanrao Kulkarni [kulsmadya@rediffmail.com]

 int getMaxRecords()
          A DB Object can be told to only retrieve a certain number of records.
 String getMyKeys()
          Get a string consisting of the values of each key field for this object appended together with a | between them.
protected  Object[] getMyUpdatesArray()
          Return the array of updates (see the inner class) that specify what changes were just made to this object.
 int getOffsetRecord()
          Gets the number of records that be skipped.
protected  org.apache.oro.text.regex.PatternMatcher getPatternMatcher()
          Retrieve a thread local instance of the Perl5 pattern matcher.
 int getPrecision(String fieldName)
          Get the precision of thie field, if one was specified
 String getSerializedForm(DBField theField)
          This function is called whenever the DBField is about to be written to the database.
 String getStringFilter(String fieldName)
          get the current filter for a particular field.
static DBObject getThisDBbj(DataTransferObject dto)
          Constructor method that takes a DataTransferObject and builds a full fledged DBObject out of it.
protected  DBObject getThisDBObj()
          This will return a new object of the type of the subclass.
 String getValidValueDescrip(String fieldName)
          This is a convenience method which will return a ValidValue description for a multi-valued field.
 Vector getValidValues(String fieldName)
          New method to replace getValues with a structure of valid values and descriptions.
 List getValidValuesList(String fieldName)
          Retrieve a list of valid value object for this particular dbobject
 Vector getValues()
          Method to return a Vector of ValidValue Template method--not implemented in this superclass.
protected  Vector getValuesDefault(String valueField, String descripField)
          Basic version of getValidValues that stores/retrieves the valid values in a Cache.
protected  Vector getValuesDefault(String valueField, String descripField, String whereClause)
          Basic filtered version of getValidValues that stores/retrieves the valid values in a Cache.
protected  Vector getValuesDefault(String valueField, String descripField, String whereClause, String sortKeyString)
          Basic version of getValidValues that stores/retrieves the valid values in a Cache.
 boolean hasError(String fieldName)
          Use this to check if a field is in error.
 boolean hasErrors()
          Use this to check if any fields are in error.
 boolean haveAllKeys()
          See if we have a value for each of the key fields
protected  void initialize()
          Sets up metadata for the dbobject via call to setupFields().
 boolean isCached()
          Is this object using internal caching?
 boolean isChanged()
          summarize DataField.isChanged() for all fields.
 boolean isDistinct()
          This method iterates through all the DBFields belonging DBObject returns true if any of them are set a distinct.
 boolean isEmpty()
          Return true if every field in this object is empty or null.
 boolean isFieldDistinct(String fieldName)
          Convenience method to check if a field is distinct or not within this database object.
 boolean isFieldNull(String fieldName)
          Tells whether a particular field is null or not.
 boolean isFieldsToRetrieve()
          This method iterates through all the DBFields belonging DBObject returns true if any of them are between the retrieve fields.
 boolean isFieldToRetrieve(String fieldName)
          Convenience method to check if a field is field to be retrieve or not within this database object.
 boolean isMultiValued(String fieldName)
          Deprecated. since 5.6, use getJDBCMetaData().isMultiValued(String)
 boolean isReadOnly(String fieldName)
          Deprecated. since 5.6, use getJDBCMetaData().isReadOnly(String)
 boolean isSecret(String fieldName)
          Deprecated. since 5.6, use getJDBCMetaData().isSecret(String)
 boolean isVirtual(String fieldName)
          Deprecated. since 5.6, use getJDBCMetaData().isVirtual(String)
 int loadFromConnection(DBConnection connection)
          Hand a dbobject a connection that contains fields corresponding to what the dbobject expects, and it'll set itself.
protected  void logChange(DBField oneField, String fieldValue)
          Helper Function: If Change Logging is enabled, then this logs what has changed
 double max(String fieldName)
          Find the maximum of the values in the specified field of records se;lected by the DBObject selection criteria.
 double min(String fieldName)
          Find the minimum of the values in the specified field of records selected by the DBObject selection criteria.
 DBObject newInstance()
          get a new instance of this object, with some basic attributes copied, like the local connection of the transaction

Generally speaking, DO NOT OVERRIDE THIS METHOD.

protected  String noNewLine(String fieldValue)
          Strip out the newlines out of a string
protected  String noQuotes(String oldString)
          Utility method to return a string with all single quotes replaced with a pair of single quotes, and all double quotes also replaced with a pair of single quotes
protected  void notifyListeners(String eventCode)
          Used by internal caching to ensure that caches are cleared when an update is made.
 void populateDefaultValues()
          populateDefaultValues is called by the schema object to allow a table to populate itself with any desired values.
protected  void referredToBy(DBObject refObject, String foreignKeyNames, String errorMessage)
          The reverse of the checkRef method - if this object is referred to by some other object, and we are changing our own key (only allowed by deleting) then check the other table to make sure our key is not being used by it!
 void removeAttribute(String attributeName)
          Removes an attribute from this particular database object.
 void removeFromCache(DBObject theDBObj)
          Remove a specific object from that object's cache.
 void retrieve()
          Get a particular record from the database into this object's fields Key fields for this object must be set; throws otherwise
 boolean retrieveFromCache()
          Retrieve this object from cache, if possible.
 void saveBinaryField(String fieldName, byte[] incomingData)
          Deprecated. since Expresso 5.6. Use LobField directly or com.jcorporate.expresso.services.dbobj.MediaDBObject for BLOB storage since they all require much less memory as well as provides more dynamic database support.
 void search()
          Find a set of keys of all of the objects that match the current search critieria in the fields.
 void search(String sortKeyString)
          Second form of search: takes a list of sort keys & calls regular search.
 ArrayList searchAndRetrieveList()
          Find a set of records of all of the objects that match the current search critieria in the fields and retrieve the list of all records that match this criteria NOTE: Criteria in 'text' type colums is ignored (SQL Server limitation)

SIDE-EFFECT: custom 'where' clause is set to null.

 ArrayList searchAndRetrieveList(String sortKeyString)
          Search and retrieve in a particular order
 void set(String fieldName, Object o)
          sets the field value by using 'instanceof' operator; convenient for template methods, but less efficient than calling setField()
 void setAttribute(String attribName, Object attribValue)
          Set an attribute.
 void setCacheSize()
          Read the configuration table to determine the max size of the cache for this db object.
 void setCharset(String newCharSet)
          Set a characterset for a particular field.
 void setCheckZeroUpdate(boolean newFlag)
          Turn on or off the facility to verify that when an update is made that at least one record got updated.
 void setConnection(DBConnection newConnection)
          Set a specific DB connection for use with this db object.
 void setConnection(DBConnection newConnection, String setupTablesContext)
          

Set a specific DB connection for use with this db object.

 void setCustomWhereClause(String newCustomWhere)
          Specify a custom "where" clause for the SQL used to retrieve records for this object.
 void setCustomWhereClause(String newCustomWhere, boolean append)
          Allows us to specify a custom WHERE clause and have it appended to the one built from the field values in the object
 void setDataContext(String newContext)
          Sets the data context that this object is residing in.
 void setDataField(String fieldName, DataField o)
          Same as setField, but works with the DataObject Interface
 void setDataTransferObject(DataTransferObject dto)
          fill fields with values found in dto; REPLACES any data field already present.
protected  void setDefaultValue(String fieldName, String fieldValue)
          Define a "default" value for a field - to be used for the field when the user does not specify a value.
 void setDescription(String newDescription)
          Set the description of this object
 void setField(String fieldName, BigDecimal fieldValue)
          BigDecimal object Typesafe version of setField.
 void setField(String fieldName, boolean fieldValue)
          Boolean typesafe version of setField
 void setField(String fieldName, byte fieldValue)
          Byte primitive integer Typesafe version of setField.
 void setField(String fieldName, byte[] fieldValue)
          Byte primitive integer Typesafe version of setField.
 void setField(String fieldName, Date fieldValue)
          Date object Typesafe version of setField.
 void setField(String fieldName, double fieldValue)
          Double primitive Typesafe version of setField.
 void setField(String fieldName, int fieldValue)
          Integer primitive Typesafe version of setField.
 void setField(String fieldName, long fieldValue)
          Long primitive Typesafe version of setField.