org.tentackle.db
Class DbObject

java.lang.Object
  extended by org.tentackle.db.DbObject
All Implemented Interfaces:
Serializable, Cloneable, Comparable<DbObject>
Direct Known Subclasses:
AppDbObject, DbPreferencesKey, DbPreferencesNode, ModificationLog, ObjectId, PartialDbObject

public abstract class DbObject
extends Object
implements Serializable, Comparable<DbObject>, Cloneable

Database object.

All database objects must extend DbObject, which provides the generic functionality of persistent objects. Every DbObject is associated to a logical Db connection, which can be either local or remote. The application-specific configuration is achieved by implementing and/or overriding methods (pure OO-approach). These methods are generated by wurblets (see http://www.wurbelizer.org) which are already provided by Tentackle.

DbObjects have the following predefined attributes:

By default, all dbobject classes use ObjectId as their common IdSource. However, that can be changed on a per-class basis by providing a property file.

See Also:
Serialized Form

Nested Class Summary
static interface DbObject.CopyAllToDbLogger
          The logger for copyAllToDb(org.tentackle.db.Db, boolean, org.tentackle.db.DbObject.CopyAllToDbLogger).
static class DbObject.IdComparator<T extends DbObject>
          Compares the IDs.
static class DbObject.NameComparator<T extends DbObject>
          Compares the string representation (toString()).
static class DbObject.NameIdComparator<T extends DbObject>
          Compares the names + IDs.
 
Field Summary
static char BEGIN
          modification type: begin transaction
static char COMMIT
          modification type: commit transaction
static char DELETE
          modification type: object deleted
static char DELETEALL
          modification type: all objects of given type deleted
static String FIELD_ID
          name of ID column
static String FIELD_SERIAL
          name of serial column
static String FIELD_TABLESERIAL
          name of tableserial column
static DbObject.IdComparator<DbObject> idComparator
          ID comparator
static char INSERT
          modification type: object inserted
static long lazyMethodInterval
          Interval in [ms] to avoid invocation bursts of some methods due to swing's event model.
static DbObject.NameComparator<DbObject> nameComparator
          name comparator
static DbObject.NameIdComparator<DbObject> nameIdComparator
          name + ID comparator
static String TX_DELETE_LIST
          transaction name: delete list
static String TX_DELETE_MISSING_IN_LIST
          transaction name: delete missing in list
static String TX_DELETE_OBJECT
          transaction name: delete object
static String TX_DUMMY_UPDATE
          transaction name: dummy update
static String TX_INSERT_OBJECT
          transaction name: insert object
static String TX_INSERT_PLAIN
          transaction name: insert plain
static String TX_SAVE
          transaction name: save
static String TX_SAVE_LIST
          transaction name: save list
static String TX_UPDATE_OBJECT
          transaction name: update object
static String TX_UPDATE_PLAIN
          transaction name: update plain
static String TX_UPDATE_SERIAL
          transaction name: update serial
static String TX_UPDATE_SERIAL_AND_TABLESERIAL
          transaction name: update serial and tableserial
static String TX_UPDATE_TABLESERIAL
          transaction name: update tableserial
static char UPDATE
          modification type: object updated
 
Constructor Summary
DbObject()
          Creates a database object not associated to a logical Db-connection.
DbObject(Db db)
          Creates a database object.
 
Method Summary
 void _delete()
          Wrapper for delete().
 void _save()
          Wrapper for save().
 boolean alwaysPrepare()
          Determines whether prepared statements of this class should always be prepared each time when the statement used.
protected  void assertLazyNotWithinTX()
          Asserts that lazy method is not used within a transaction.
 boolean attributesModified()
          Determines whether this object got some of its attributes modified.
It does not check whether some of its composites are modified! This method can also be used for non-tracked objects.
protected  boolean beginTx(String txName)
          Begins a transaction.
Also sets the txObject if a transaction is started or isTxObject() returns true.
 DbObject clone()
          Clones an object.
 int compareTo(DbObject obj)
          Compare two objects.
We are using the ID to compare objects.
 int copyAllToDb(Db destDb, boolean plain, DbObject.CopyAllToDbLogger logger)
          Copies all objects of this class to another db.
 void copyLazyValues(DbObject obj)
          Copies the lazy values from one object to another.
 boolean copyToDb(Db destDb, boolean plain)
          Copies an object from one db connection to another.
 long countModification()
          Counts a modification for the class of this object with optimization.
 long countModification(boolean optimize)
          Counts a modification for the class of this object.
 ModificationLog createModificationLog(char modType)
          Creates a ModificationLog.
 boolean delete()
          Removes this object from the database (with linked objects, i.e.
 boolean deleteLinkedObjects()
          Deletes all linked objects
static int deleteList(List<? extends DbObject> list)
          Deletes a List of objects.
static int deleteMissingInList(List<? extends DbObject> oldList, List<? extends DbObject> newList)
          Deletes all objects in oldList that are not in newList.
 boolean deleteObject(boolean withLinkedObjects)
          Removes this object from the database.
Note: this method should be used by the application with great care! Use delete() instead!
 boolean deletePlain()
          Deletes this object from the database without any further processing (i.e.
 boolean dummyUpdate()
          Performs a dummy update.
The method is provided as an alternative to reloadLocked() or selectLocked(long, boolean) to lock the object during a transaction by updating the ID without changing it.
 boolean equals(Object object)
          Objects are identical if their IDs and classes are identical.
 boolean finishModification(char modType)
          Does any postprocessing after delete, insert or update.
 boolean finishNotUpdated()
          Does any update postprocessing for objects not being updated (because not modified for some reason, e.g.
 String getClassBaseName()
          Gets the basename of the class of this object.
The basename is the class name without the package name.
 String getClassName()
          Gets the class name of this object.
This is equivalent to getClass().getName() except for PartialDbObjects!
 Db getDb()
          Get the logical db connection for this object.
abstract  DbObjectClassVariables getDbObjectClassVariables()
          Gets the some attributes and variables common to all objects of the same class.
protected  int getDeleteStatementId()
          Gets the prepared statement id for delete().
protected  int getDummyUpdateStatementId()
          Gets the prepared statement id for dummyUpdate().
 long[] getExpirationBacklog(long minSerial, long maxSerial)
          Gets the expiration backlog for a given range of tableserials.
 long[] getExpiredTableSerials(long oldSerial, long maxSerial)
          Combines selectExpiredTableSerials(long) and getExpirationBacklog(long, long).
A physical database query is only done if the requested range is not in the backlog.
 int getFieldCount()
          Gets the number of columns (fields) in the table corresponding to the class of this object.
The method does a dummy select if not known so far.
abstract  boolean getFields(ResultSetWrapper rs)
          Retrieves the values of all fields (all columns of the database table) in the given ResultSetWrapper and stores them in the object's attributes.
 ImageIcon getIcon()
          Gets the icon of this object.
 long getId()
          Gets the object ID.
 IdSource getIdSource()
          Get the IdSource.
protected  int getInsertStatementId()
          Gets the prepared statement id for insert().
 String getMultiName()
          Gets the human readable name for multiple (> 1) objects of this class.
 DbObjectRemoteDelegate getRemoteDelegate()
          Gets the delegate for remote connections.
Each class has its own delegate.
protected  int getRemoteDelegateId()
          Returns the ID of the delegate for the class of this object.
protected  int getSelectAllStatementId()
          Gets the prepared statement id for selectAll(boolean).
protected  int getSelectExpiredTableSerials1StatementId()
          Gets the prepared statement id for selectExpiredTableSerials(long).
protected  int getSelectExpiredTableSerials2StatementId()
          Gets the prepared statement id for selectExpiredTableSerials(long).
protected  int getSelectLockedStatementId()
          Gets the prepared statement id for selectLocked(long, boolean).
protected  int getSelectSerialStatementId()
          Gets the prepared statement id for selectSerial(long).
protected  int getSelectStatementId()
          Gets the prepared statement id for select(long, boolean).
 long getSerial()
          Gets the serial number.
 String getSingleName()
          Gets the human readable name for one (1) object of this class.
 String getSqlAllFields()
          Gets the sql text to select all fields (and all objects).
 String getSqlPrefix()
          Column names may be preceeded by a prefix.
 String getSqlPrefixWithDot()
          Gets the prefix with a trailing dot or "" if no prefix.
 String getSqlSelectAllFields()
          Get the SQL-string to select all columns of this class (may be across multiple tables)
 String getTableName()
          Gets the database table name for the class of this object.
 long getTableSerial()
          Gets the table serial.
protected  int getUpdateSerialAndTableSerialStatementId()
          Gets the prepared statement id for updateSerialAndTableSerial().
protected  int getUpdateSerialStatementId()
          Gets the prepared statement id for updateSerial().
protected  int getUpdateStatementId()
          Gets the prepared statement id for update().
protected  int getUpdateTableSerialStatementId()
          Gets the prepared statement id for updateTableSerial().
 int hashCode()
          The hashcode for a Db-object is simply the ID.
 boolean initModification(char modType)
          Does any preprocessing before delete, insert or update.
 boolean insert()
          Inserts this (new) object into the database with linked objects.
 boolean insertObject(boolean withLinkedObjects)
          Inserts this (new) object into the database.
 boolean insertPlain()
          Insert this object into the database without any further processing (i.e.
 void invalidateLazyValues()
          Clears the lazy values.
Makes it safe to invoke the lazy method and being sure to invoke the non-lazy too.
 boolean isCountingModification(int modType)
          Determines whether modifications of this object are counted in the modification table.
 boolean isDeleted()
          Checks whether object is deleted (or got a reserved ID).
 boolean isEditable()
          Checks whether this object can be edited by the user.
 boolean isEditableLazy()
          Gets the editable state which has been valid for at least the last lazyMethodInterval milliseconds.
 boolean isEntity()
          Returns whether instances of this class exist as database entities.
 boolean isGettingFieldCount()
          As getFieldCount() is invoked from getFields(org.tentackle.db.ResultSetWrapper) this prevents a heap overflow.
 boolean isIdValid()
          Checks whether the object has a valid ID, i.e.
 boolean isLazyElapsed()
          For the GUI a lazy method is provided to reduce the invocations.
static boolean isListModified(List<? extends DbObject> list)
          Checks whether some of the objects in the list are modified.
 boolean isLoggingModification(int modType)
          Determines whether each modification of this object (with respect to the database) should be logged.
 boolean isModified()
          Determines whether the object should be written to persistant storage because it has been modified.
 boolean isNew()
          Checks whether this object is already persistant in the db or only residing in memory.
 boolean isPartial()
          Returns true if object is only a partial implementation.
 boolean isReferenced()
          Checks whether this object is referenced by other objects.
 boolean isReferencedLazy()
          Gets the referenced state which has been valid for at least the last lazyMethodInterval milliseconds.
 boolean isRemovable()
          Checks whether this object can be removed.
 boolean isRemovableLazy()
          Gets the removeable state which has been valid for at least the last lazyMethodInterval milliseconds.
 boolean isSaveable()
          Determines whether this object is allowed to be stored in DB.
The default is true.
 boolean isTableSerialValid()
          By default objects don't need to include the tableSerial in the database table.
 boolean isTracked()
          Checks if modification of this object are tracked, i.e.
 boolean isTxObject()
          Determines whether this object becomes the txObject (see Db.setTxObject(org.tentackle.db.DbObject)) within a transaction.
 boolean isUpdatingSerialEvenIfNotModified()
          Determines whether in updates of composite objects unmodified objects in the update path get at least the serial updated or are not touched at all.
 boolean isVirgin()
          Checks whether this object ever was stored in the database.
 boolean loadLinkedObjects()
          Loads all linked objects.
 boolean logModification(char modType)
          Logs a modification for this object to the modlog (not to be mixed up with the modification-counter!)
 void markDeleted()
          Marks an object to be deleted.
This is done by negating its id.
static int markListDeleted(List<? extends DbObject> list)
          Marks all objects in a list to be deleted.
Use this method if a list-SQL-delete removed a set of objects and you have to reflect that in the list of objects.
static
<T extends DbObject>
T
newByClass(Class<T> clazz)
          Instantiates a new object for a given class (without db-context).
static
<T extends DbObject>
T
newByClass(Db db, Class<T> clazz)
          Instantiates a new object for a given class and db.
static
<T extends DbObject>
T
newByClassWrapped(Class<T> clazz)
          Instantiates a new object for a given class transforming exceptions to DbRuntimeException.
 void newId()
          Obtains a new ID for this object.
 DbObject newObject()
          Creates a new object with the same class and same logical db connection as this object.
 int prepareDeleteStatement()
          Prepares the delete statement (usually the same for all objects)
 int prepareDummyUpdateStatement()
          Prepares the dummy update.
abstract  int prepareInsertStatement()
          Prepares the insert statement.
 int prepareSelectLockedStatement()
          Prepares the select statement with lock (usually the same for all objects)
 int prepareSelectSerialStatement()
          Prepares the selectSerial statement (usually the same for all objects)
 int prepareSelectStatement()
          Prepares the select statement (usually the same for all objects)
 boolean prepareSetFields()
          Prepares the object's attributes before the object is saved to the database.
 int prepareUpdateSerialAndTableSerialStatement()
          Prepares the serial + tableSerial update.
 int prepareUpdateSerialStatement()
          Prepares the serial update.
abstract  int prepareUpdateStatement()
          Prepare the update statement.
 int prepareUpdateTableSerialStatement()
          Prepares the tableSerial update.
 boolean readFromResultSetWrapper(ResultSetWrapper rs)
          Reads the values from a result-set into this object.
 boolean readFromResultSetWrapper(ResultSetWrapper rs, boolean withLinkedObjects)
          Reads the values from a result-set into this object.
 DbObject reload()
          Reloads the object.
 DbObject reloadLocked()
          Reloads the object with a write lock.
 void reserveId()
          Reserves an ID.
 boolean save()
          Saves this object.
This is the standard method applications should use to insert or update objects.
 boolean saveLinkedObjects()
          Saves all linked objects.
static int saveList(List<? extends DbObject> list)
          Saves a list of objects.
The linked objects are saved as well.
static int saveList(List<? extends DbObject> list, boolean modifiedOnly)
          Saves a list of DbObjects.
All objects with isSaveable() == true will be saved.
static
<T extends DbObject>
T
select(Db db, Class<T> clazz, long id)
          Selects an object for a given class and db by its unique id.
static
<T extends DbObject>
T
select(Db db, String className, long id)
          Selects an object for a given class name and db by its unique id.
 DbObject select(long id)
          Loads an object from the database by its unique ID.
 DbObject select(long id, boolean withLinkedObjects)
          Loads an object from the database by its unique ID.
 List<? extends DbObject> selectAll()
          Selects all objects of this class as a List.
 List<? extends DbObject> selectAll(boolean withLinkedObjects)
          Selects all objects of this class as a List.
static
<T extends DbObject>
List<T>
selectAll(Db db, Class<T> clazz)
          Selects all objects of this class.
 DbCursor<? extends DbObject> selectAllCursor()
          Selects all objects of this class as a DbCursor.
 DbCursor<? extends DbObject> selectAllCursor(boolean withLinkedObjects)
          Selects all objects of this class as a DbCursor.
 ResultSetWrapper selectAllResultSet()
          Selects all objects of this class and returns the ResultSetWrapper.
 long[] selectExpiredTableSerials(long oldSerial)
          Determines the objects with a tableSerial starting at a given serial.
 long[] selectExpiredTableSerials(long oldSerial, long maxSerial)
          Determines the objects with their tableSerial within a given range.
 DbObject selectInValidContext(long id, boolean withLinkedObjects)
          Same as select(long, boolean) but makes sure that the object is selected in a valid context, i.e.
 DbObject selectLocked(long id)
          Load the object from the database with exclusive lock (aka write lock).
 DbObject selectLocked(long id, boolean withLinkedObjects)
          Load the object from the database with exclusive lock (aka write lock).
 long selectModification()
          Selects the current modification counter for the class of this object.
 DbObject selectNext(ResultSetWrapper rs, boolean withLinkedObjects)
          Selects the next object from a resultset.
 long selectSerial()
          Selects the serial-number for this object.
 long selectSerial(long id)
          Selects the serial-number for a given object id.
 void setAlwaysPrepare(boolean alwaysPrepare)
          Sets the always prepare flag.
 void setDb(Db db)
          Sets the logical db connection for this object.
protected  void setDeleteStatementId(int id)
          Sets the prepared statement id for delete().
protected  void setDummyUpdateStatementId(int id)
          Sets the prepared statement id for dummyUpdate().
abstract  int setFields(PreparedStatementWrapper st)
          Sets the values of all fields (all columns of the database table) in the given PreparedStatementWrapper from the object's attributes.
 void setId(long id)
          Sets the unique ID of this object.
protected  void setInsertStatementId(int id)
          Sets the prepared statement id for insert().
 void setModified(boolean modified)
          Sets the modified flag.
protected  void setSelectAllStatementId(int id)
          Sets the prepared statement id for selectAll(boolean).
protected  void setSelectExpiredTableSerials1StatementId(int id)
          Sets the prepared statement id for selectExpiredTableSerials(long).
protected  void setSelectExpiredTableSerials2StatementId(int id)
          Sets the prepared statement id for selectExpiredTableSerials(long).
protected  void setSelectLockedStatementId(int id)
          Sets the prepared statement id for selectLocked(long, boolean).
protected  void setSelectSerialStatementId(int id)
          Sets the prepared statement id for selectSerial(long).
protected  void setSelectStatementId(int id)
          Sets the prepared statement id for select(long, boolean).
 void setSerial(long serial)
          Sets the serial number (modification count).
 void setTableSerial(long tableSerial)
          Sets the table serial number (table modification count).
protected  void setUpdateSerialAndTableSerialStatementId(int id)
          Sets the prepared statement id for updateSerialAndTableSerial().
protected  void setUpdateSerialStatementId(int id)
          Sets the prepared statement id for updateSerial().
protected  void setUpdateStatementId(int id)
          Sets the prepared statement id for update().
protected  void setUpdateTableSerialStatementId(int id)
          Sets the prepared statement id for updateTableSerial().
 boolean sync()
          Try to update an object first and if that failes, try to insert.
This method is used for transferring an Object from one DB to another as it is the case in RMI-connections, where the ID is transmitted, but the object may or may not exist in the other database.
 boolean syncObject(boolean withLinkedObjects)
          Try to update an object first and if that failes, try to insert.
This method is used for transferring an Object from one DB to another as it is the case in RMI-connections, where the ID is transmitted, but the object may or may not exist in the other database.
 String toGenericString()
          Gets the string value: "getSingleName()[id/serial]".
Example: "Product[344/2]"
 String toString()
          Gets the default string value.
The default implementation invokes toGenericString().
 boolean update()
          Updates this object to the database.
The modified attribute gets cleared if insert was successful.
protected  void updateFieldCount(int columnIndex)
          Updates the fieldCount in the class variables if the given columnIndex is greater than current fieldcount.
 int updateFields(ResultSetWrapper rs)
          Updates the fields in the result-set.
Because it is only used in updateable cursors and by far most apps don't use that feature, the method is not abstract and by default throws the exception for "not implemented".
 boolean updateObject(boolean withLinkedObjects)
          Updates this object to the database.
The modified attribute gets cleared if insert was successful.
 boolean updatePlain()
          Updates this object to the database without any further processing (i.e.
 boolean updateSerial()
          Updates and increments the serial number of this object.
The method is provided to update an object with isModified() == true and 'modified' == false, i.e.
 boolean updateSerialAndTableSerial()
          Same as updateSerial() but updates tableSerial as well.
 boolean updateTableSerial()
          Updates the tableSerial only.
The method is provided to explicitly force this object to expire in caches.
 
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait
 

Field Detail

lazyMethodInterval

public static long lazyMethodInterval
Interval in [ms] to avoid invocation bursts of some methods due to swing's event model. See isEditableLazy(), for example.


idComparator

public static DbObject.IdComparator<DbObject> idComparator
ID comparator


nameComparator

public static DbObject.NameComparator<DbObject> nameComparator
name comparator


nameIdComparator

public static DbObject.NameIdComparator<DbObject> nameIdComparator
name + ID comparator


FIELD_ID

public static String FIELD_ID
name of ID column


FIELD_SERIAL

public static String FIELD_SERIAL
name of serial column


FIELD_TABLESERIAL

public static String FIELD_TABLESERIAL
name of tableserial column


BEGIN

public static final char BEGIN
modification type: begin transaction

See Also:
Constant Field Values

COMMIT

public static final char COMMIT
modification type: commit transaction

See Also:
Constant Field Values

INSERT

public static final char INSERT
modification type: object inserted

See Also:
Constant Field Values

UPDATE

public static final char UPDATE
modification type: object updated

See Also:
Constant Field Values

DELETE

public static final char DELETE
modification type: object deleted

See Also:
Constant Field Values

DELETEALL

public static final char DELETEALL
modification type: all objects of given type deleted

See Also:
Constant Field Values

TX_INSERT_PLAIN

public static final String TX_INSERT_PLAIN
transaction name: insert plain

See Also:
Constant Field Values

TX_INSERT_OBJECT

public static final String TX_INSERT_OBJECT
transaction name: insert object

See Also:
Constant Field Values

TX_UPDATE_PLAIN

public static final String TX_UPDATE_PLAIN
transaction name: update plain

See Also:
Constant Field Values

TX_DUMMY_UPDATE

public static final String TX_DUMMY_UPDATE
transaction name: dummy update

See Also:
Constant Field Values

TX_UPDATE_SERIAL

public static final String TX_UPDATE_SERIAL
transaction name: update serial

See Also:
Constant Field Values

TX_UPDATE_SERIAL_AND_TABLESERIAL

public static final String TX_UPDATE_SERIAL_AND_TABLESERIAL
transaction name: update serial and tableserial

See Also:
Constant Field Values

TX_UPDATE_TABLESERIAL

public static final String TX_UPDATE_TABLESERIAL
transaction name: update tableserial

See Also:
Constant Field Values

TX_UPDATE_OBJECT

public static final String TX_UPDATE_OBJECT
transaction name: update object

See Also:
Constant Field Values

TX_SAVE

public static final String TX_SAVE
transaction name: save

See Also:
Constant Field Values

TX_DELETE_OBJECT

public static final String TX_DELETE_OBJECT
transaction name: delete object

See Also:
Constant Field Values

TX_SAVE_LIST

public static final String TX_SAVE_LIST
transaction name: save list

See Also:
Constant Field Values

TX_DELETE_LIST

public static final String TX_DELETE_LIST
transaction name: delete list

See Also:
Constant Field Values

TX_DELETE_MISSING_IN_LIST

public static final String TX_DELETE_MISSING_IN_LIST
transaction name: delete missing in list

See Also:
Constant Field Values
Constructor Detail

DbObject

public DbObject(Db db)
Creates a database object.

Parameters:
db - the logical Db-connection

DbObject

public DbObject()
Creates a database object not associated to a logical Db-connection. The connection must be set via setDb(org.tentackle.db.Db) in order to use it.

Method Detail

toString

public String toString()
Gets the default string value.
The default implementation invokes toGenericString().

Overrides:
toString in class Object
Returns:
the string value of this DbObject

toGenericString

public String toGenericString()
Gets the string value: "getSingleName()[id/serial]".
Example: "Product[344/2]"

Returns:
the string value of this DbObject

getDbObjectClassVariables

public abstract DbObjectClassVariables getDbObjectClassVariables()
Gets the some attributes and variables common to all objects of the same class. Class variables for classes derived from DbObject are kept in an instance of DbObjectClassVariables.

Returns:
the class variables

getClassBaseName

public String getClassBaseName()
Gets the basename of the class of this object.
The basename is the class name without the package name.

Returns:
the basename of the Objects class

getClassName

public String getClassName()
Gets the class name of this object.
This is equivalent to getClass().getName() except for PartialDbObjects!

Returns:
the classname

clone

public DbObject clone()
Clones an object.

Cloning an object yields a copy with id=0 and serial=0. Needs to be overridden if object references, etc... have to be cloned too. Subclasses should throw a DbRuntimeException if they should not be cloned depending on the application logic (not CloneNotSupportedException).

Overrides:
clone in class Object
Returns:
a clone of this object
See Also:
Cloneable

isPartial

public boolean isPartial()
Returns true if object is only a partial implementation. This is used in conjunction with PartialAppDbObject and the wurblet AppDbSuper for abstract super classes in a table-per-class mapping.

Returns:
true if partial implementation

isEntity

public boolean isEntity()
Returns whether instances of this class exist as database entities. The default is true. An example of a non-entity object is PartialDbObject.

Returns:
true if entity

newObject

public DbObject newObject()
Creates a new object with the same class and same logical db connection as this object. Must be overridden if further setup is necessary.

Returns:
the new object

setDb

public void setDb(Db db)
Sets the logical db connection for this object.

Parameters:
db - the db connection

getDb

public Db getDb()
Get the logical db connection for this object.

Returns:
the db connection

setId

public void setId(long id)
Sets the unique ID of this object. Does not set this object to be modified, see isModified().

Parameters:
id - the object id

getId

public long getId()
Gets the object ID. If the object is deleted (negated ID) the returned ID is still positive!

Returns:
the object id

setSerial

public void setSerial(long serial)
Sets the serial number (modification count). Does not set this object to be modified, see isModified().

Parameters:
serial - the serial number

getSerial

public long getSerial()
Gets the serial number.

Returns:
the serial number.

setTableSerial

public final void setTableSerial(long tableSerial)
Sets the table serial number (table modification count). Does not set this object to be modified, see isModified().

Parameters:
tableSerial - the new table serial

getTableSerial

public long getTableSerial()
Gets the table serial.

Returns:
the table serial

newId

public void newId()
Obtains a new ID for this object.

If the object already has an ID or is deleted (negative ID) the ID will _not_ change.


reserveId

public void reserveId()
Reserves an ID.

Reserved IDs are negative. A new object with a reserved ID can be distinguished from a deleted object by its serial. See also isVirgin(). If the object already has an ID or is deleted (negative ID) the ID will _not_ change.


isNew

public boolean isNew()
Checks whether this object is already persistant in the db or only residing in memory. If an object isNew(), it means that it can be inserted. This does not mean, that the object never has been stored in the db, i.e. it is possible that the object just has been deleted.

Returns:
true if object is not in database, i.e. new (or deleted)

isIdValid

public boolean isIdValid()
Checks whether the object has a valid ID, i.e. not 0.

Returns:
true if object got a valid id, whether deleted or not

isDeleted

public boolean isDeleted()
Checks whether object is deleted (or got a reserved ID). A deleted object with a reserved ID can be distinguished from an object with a reserved ID by its serial. See also isVirgin().

Returns:
true if object has been deleted

isVirgin

public boolean isVirgin()
Checks whether this object ever was stored in the database. Virgin objects have a serial of zero. Notice that an object is still "virgin", if it got a valid id via reserveId() but has not been saved so far.

Returns:
true if object is virgin, false if it is or was stored in the database.

setModified

public void setModified(boolean modified)
Sets the modified flag.

For optimizations it is possible to skip objects that have not been modified. The modified-attribute is cleared whenever the object is saved (inserted or updated -- NOT insertPlain and updatePlain!). The application is responsible to set the modified flag! This is usually done in the setter-methods of the db-attributes. The wurblet 'DbMethods' does this for you with option '--tracked'

Parameters:
modified - is true if object is flagged modified, false if not.

isTracked

public boolean isTracked()
Checks if modification of this object are tracked, i.e. setModified() is called properly. By default, DbObjects are *NOT* tracked! This is quality measure to ensure that isModified() returns false if and only if it hasn't been modified, i.e. the setters check for modification. See the wurblet DbMethods.

Returns:
true if tracked, false otherwise (default)

isModified

public boolean isModified()
Determines whether the object should be written to persistant storage because it has been modified.

By definition, an object is 'modified' if the object OR ANY of its composites are modified. See DbRelations.wrbl on how and when to override isModified().

New objects are modified by definition! Furthermore, isModified() will invoke the errorhandler if isTracked() != true. DbMethods automatically override this method if option --tracked is given.

Returns:
true if object is modified and should be saved().

attributesModified

public boolean attributesModified()
Determines whether this object got some of its attributes modified.
It does not check whether some of its composites are modified! This method can also be used for non-tracked objects.

Returns:
true if this object

isSaveable

public boolean isSaveable()
Determines whether this object is allowed to be stored in DB.
The default is true. Objects not allowed to be saved will force save(), insert() and update() to return 'false' and silently skipped in saveList().

Returns:
true if saveable

loadLinkedObjects

public boolean loadLinkedObjects()
Loads all linked objects.

Note: Linked objects are not to be mixed up with composites. See the wurblet AppDbRelations for how this method is used.

Returns:
true if all object loaded

saveLinkedObjects

public boolean saveLinkedObjects()
Saves all linked objects.

Note: Linked objects are not to be mixed up with composites. See the wurblet AppDbRelations for how this method is used.

Returns:
true of all objects saved

deleteLinkedObjects

public boolean deleteLinkedObjects()
Deletes all linked objects

Note: Linked objects are not to be mixed up with composites. See the wurblet AppDbRelations for how this method is used.

Returns:
true of all objects deleted

getIcon

public ImageIcon getIcon()
Gets the icon of this object. The icon is displayed in trees, for example. The default implementation returns PlafGlobal.getIcon(java.lang.String, java.lang.String)("unknown").

Returns:
the icon

isReferenced

public boolean isReferenced()
Checks whether this object is referenced by other objects.

It is invoked before operations that may have an impact on the referential integrity. The default implementation returns false.

The application can assume a lazy context (invoked from is...Lazy) if invoked outside a transaction. This is just an optimization hint.

Returns:
true if referenced

isRemovable

public boolean isRemovable()
Checks whether this object can be removed.

It is invoked before operations that may have an impact on the referential integrity. The default implementation returns true if !isNew and !isReferenced. Does not refer to the SecurityManager!

The application can assume a lazy context (invoked from is...Lazy) if invoked outside a transaction. This is just an optimization hint.

Notice that isRemovable() for performance reasons is not covered by its own delegate method in remote connections. Hence, if classes in your application require a different implementation (!isNew && !isReferenced) you must provide such a remote method.

Returns:
true if removable

isEditable

public boolean isEditable()
Checks whether this object can be edited by the user.

The default implementation returns true. Does not refer to the SecurityManager!

The application can assume a lazy context (invoked from is...Lazy) if invoked outside a transaction. This is just an optimization hint.

Notice that isEditable() for performance reasons is not covered by its own delegate method in remote connections. Hence, if classes in your application require a different implementation you must provide such a remote method.

Returns:
true if editable

isLazyElapsed

public boolean isLazyElapsed()
For the GUI a lazy method is provided to reduce the invocations. Use this method instead of the non-lazy one if it's just a hint for enabling certain gui-components (which is checked within a succeeding tx anyway).

Returns:
true if the lazy method should invoke the non-lazy. false if return lazy value.

copyLazyValues

public void copyLazyValues(DbObject obj)
Copies the lazy values from one object to another.

Parameters:
obj - the object to copy the values from

invalidateLazyValues

public void invalidateLazyValues()
Clears the lazy values.
Makes it safe to invoke the lazy method and being sure to invoke the non-lazy too.


assertLazyNotWithinTX

protected void assertLazyNotWithinTX()
Asserts that lazy method is not used within a transaction.


isReferencedLazy

public boolean isReferencedLazy()
Gets the referenced state which has been valid for at least the last lazyMethodInterval milliseconds.

Returns:
true if referenced

isRemovableLazy

public boolean isRemovableLazy()
Gets the removeable state which has been valid for at least the last lazyMethodInterval milliseconds.

Returns:
true if removable

isEditableLazy

public boolean isEditableLazy()
Gets the editable state which has been valid for at least the last lazyMethodInterval milliseconds.

Returns:
true if editable

isCountingModification

public boolean isCountingModification(int modType)
Determines whether modifications of this object are counted in the modification table. The default implementation returns false. Must be overridden if counting the modifications is desired.

Parameters:
modType - is one of the modtypes INSERT, UPDATE, DELETE, ...
Returns:
true if count modification, false if not.
See Also:
ModificationCounter

isTableSerialValid

public boolean isTableSerialValid()
By default objects don't need to include the tableSerial in the database table. Override this method if object contains a TABLESERIAL-column.

Returns:
true if object is using the tableSerial column, false if not.

isLoggingModification

public boolean isLoggingModification(int modType)
Determines whether each modification of this object (with respect to the database) should be logged.

Parameters:
modType - is one of the modtypes INSERT, UPDATE, DELETE, ...
Returns:
true if log modification, false if not.
See Also:
ModificationLog

equals

public boolean equals(Object object)
Objects are identical if their IDs and classes are identical. IDs are *NOT* necessarily unique among all db-tables! (see poolkeeper). Does not throw any exception, so its safe to add null-objects to set of DbObjects.

Overrides:
equals in class Object
Parameters:
object - the object to test for equality
Returns:
true if this object is the same as the obj argument; false otherwise.
See Also:
Object.hashCode(), Hashtable

compareTo

public int compareTo(DbObject obj)
Compare two objects.
We are using the ID to compare objects. Makes only sense within the same class. Must be overridden if other sortings are desired. Does not throw any exception, so its safe to add null-objects to a sorted set of DbObjects.

Specified by:
compareTo in interface Comparable<DbObject>
Parameters:
obj - the object to compare this object with
Returns:
a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

hashCode

public int hashCode()
The hashcode for a Db-object is simply the ID. It is ok -- according to the contract of hashCode() -- that objects in different tables with the same id may return the same hashcode.

Overrides:
hashCode in class Object
Returns:
a hash code value for this object.
See Also:
Object.equals(java.lang.Object), Hashtable

getIdSource

public IdSource getIdSource()
Get the IdSource. If the IdSource is null, the method will look for a property file which is the classname + ".properties". The property file must contain an idsource-line very similar to that in Db.properties. However, the "objectid" means "use the source from the db" (which is the default anyway). If there is no such file, the source from the db will be used.

Returns:
Value of property idSource.

getSqlPrefix

public String getSqlPrefix()
Column names may be preceeded by a prefix. This is especially useful for joined tables auch as "table-per-class". The prefix must contain a trailing dot, just the name. The default is null.

Returns:
the SQL prefix

getSqlPrefixWithDot

public String getSqlPrefixWithDot()
Gets the prefix with a trailing dot or "" if no prefix.

Returns:
the SQL prefix

readFromResultSetWrapper

public boolean readFromResultSetWrapper(ResultSetWrapper rs,
                                        boolean withLinkedObjects)
Reads the values from a result-set into this object.

Parameters:
rs - is the result set (wrapper)
withLinkedObjects - is true if load linked objects too
Returns:
true if values read, false if some error

readFromResultSetWrapper

public final boolean readFromResultSetWrapper(ResultSetWrapper rs)
Reads the values from a result-set into this object.

Parameters:
rs - is the result set (wrapper)
Returns:
true if values read, false if some error

select

public DbObject select(long id,
                       boolean withLinkedObjects)
Loads an object from the database by its unique ID.

For local db connections the current object's attributes will be replaced by the database values (i.e. this object is returned). For remote connections, a copy of the object in the server is returned. Hence, applications should always create a new object and invoke select and don't make any further assumptions. This applies to all select methods returning an object! Example:

    Customer customer = new Customer(db).select(customerId);
 
Since Java 1.5 covariance is supported and you should consider overriding the method and cast the return value to the appropriate class.

Parameters:
id - is the object id
withLinkedObjects - is true if load linked objects too
Returns:
object if loaded, null if no such object

select

public DbObject select(long id)
Loads an object from the database by its unique ID.

For local db connections the current object's attributes will be replaced by the database values (i.e. this object is returned). For remote connections, a copy of the object in the server is returned. Hence, applications should always create a new object and invoke select and don't make any further assumptions. This applies to all select methods returning an object! Example:

    Customer customer = new Customer(db).select(customerId);
 
Since Java 1.5 covariance is supported and you should consider overriding the method and cast the return value to the appropriate class.

Parameters:
id - is the object id
Returns:
object if loaded, null if no such object

selectLocked

public DbObject selectLocked(long id,
                             boolean withLinkedObjects)
Load the object from the database with exclusive lock (aka write lock). This is implemented via "SELECT FOR UPDATE".

Parameters:
id - is the object id
withLinkedObjects - is true if load linked objects too
Returns:
object if loaded, null if no such object

selectLocked

public DbObject selectLocked(long id)
Load the object from the database with exclusive lock (aka write lock). This is implemented via "SELECT FOR UPDATE". The linked objects are loaded as well.

Parameters:
id - is the object id
Returns:
object if loaded, null if no such object

selectInValidContext

public DbObject selectInValidContext(long id,
                                     boolean withLinkedObjects)
Same as select(long, boolean) but makes sure that the object is selected in a valid context, i.e. performs optional class specific initialization that are beyond a normal DbObject.

This method primarily is provided for being overridden by AppDbObject.selectInValidContext(long, boolean). The default implementation simply invokes select().

Parameters:
id - is the object id
withLinkedObjects - is true if load linked objects too
Returns:
object if loaded, null if no such object

reload

public DbObject reload()
Reloads the object.

Note: to make sure that any lazy inits are cleared, the returned object is always a new object.

Returns:
the object if reloaded, else null (never this)

reloadLocked

public DbObject reloadLocked()
Reloads the object with a write lock. Note: to make sure that any lazy inits are cleared, the returned object is always a new object.

Returns:
the object if reloaded, else null (never this)

selectAllResultSet

public ResultSetWrapper selectAllResultSet()
Selects all objects of this class and returns the ResultSetWrapper.

Returns:
the result set

selectNext

public DbObject selectNext(ResultSetWrapper rs,
                           boolean withLinkedObjects)
Selects the next object from a resultset. Applications should close the resultset if null is returned.

Parameters:
rs - the result set
withLinkedObjects - is true if load linked objects too
Returns:
the next object, null if end of set

selectAll

public List<? extends DbObject> selectAll(boolean withLinkedObjects)
Selects all objects of this class as a List.

Parameters:
withLinkedObjects - is true if load linked objects too
Returns:
the list of objects

selectAll

public List<? extends DbObject> selectAll()
Selects all objects of this class as a List. The linked objects are loaded as well.

Returns:
the list of objects

selectAllCursor

public DbCursor<? extends DbObject> selectAllCursor(boolean withLinkedObjects)
Selects all objects of this class as a DbCursor. Will prompt the user if too much data received.

Parameters:
withLinkedObjects - is true if load linked objects too
Returns:
the cursor, never null

selectAllCursor

public DbCursor<? extends DbObject> selectAllCursor()
Selects all objects of this class as a DbCursor. Will prompt the user if too much data received. The linked objects are loaded as well.

Returns:
the cursor, never null

selectSerial

public long selectSerial(long id)
Selects the serial-number for a given object id.

Parameters:
id - the object id
Returns:
the serial for that id, -1 if no such object

selectSerial

public long selectSerial()
Selects the serial-number for this object.

Returns:
the serial for this object, -1 object not stored in database.

copyToDb

public boolean copyToDb(Db destDb,
                        boolean plain)
Copies an object from one db connection to another.

Parameters:
destDb - the destination db
plain - is true to use insertPlain (recommended), else insert
Returns:
true if inserted in destDb, false if failed

copyAllToDb

public int copyAllToDb(Db destDb,
                       boolean plain,
                       DbObject.CopyAllToDbLogger logger)
Copies all objects of this class to another db.

Parameters:
destDb - is the destination DB
plain - is true to use insertPlain (recommended), else use insert (if superclass is abstract for example)
logger - is an optional logger (null = none)
Returns:
the number copied or a negative count - 1 if error

insertPlain

public boolean insertPlain()
Insert this object into the database without any further processing (i.e. prepareSetFields, linked objcets, mod counting, logging, etc...).

Returns:
true if object inserted, false if unique violation

deletePlain

public boolean deletePlain()
Deletes this object from the database without any further processing (i.e. linked objcets, mod counting, logging, etc...).

Returns:
true if deleted, false if no such object

updatePlain

public boolean updatePlain()
Updates this object to the database without any further processing (i.e. prepareSetFields, linked objcets, mod counting, logging, etc...).

Returns:
true if object updated, false if unique violation or no such object

dummyUpdate

public boolean dummyUpdate()
Performs a dummy update.
The method is provided as an alternative to reloadLocked() or selectLocked(long, boolean) to lock the object during a transaction by updating the ID without changing it.

Returns:
true if updated, false if no such object ID

updateSerial

public boolean updateSerial()
Updates and increments the serial number of this object.
The method is provided to update an object with isModified() == true and 'modified' == false, i.e. an object that itself is not modified but some of its composites. In such a case it is not necessary to update the whole object. However, it is sometimes necessary to update the serial to indicate 'some modification' and to make sure that this object is part of the transaction. Whether it is necessary or not depends on the application.

Returns:
true if serial
See Also:
isUpdatingSerialEvenIfNotModified()

updateSerialAndTableSerial

public boolean updateSerialAndTableSerial()
Same as updateSerial() but updates tableSerial as well. Notice: the tableSerial is NOT modified in the current object, but only in the database!

Returns:
true if serial and tableSerial updated

updateTableSerial

public boolean updateTableSerial()
Updates the tableSerial only.
The method is provided to explicitly force this object to expire in caches. Useful, for example, if only editedBy() is changed and this change should be reflected in other apps. Notice: the tableSerial is NOT modified in the current object, but only in the database!

Returns:
true if updated, else false

isUpdatingSerialEvenIfNotModified

public boolean isUpdatingSerialEvenIfNotModified()
Determines whether in updates of composite objects unmodified objects in the update path get at least the serial updated or are not touched at all. The default is to leave unmodified objects untouched. However, in some applications it is necessary to update the master object if some of its childs are updated (usually to trigger something, e.g. a cache-update).

The default implementation returns false. Override this method to change to 'true'.

Returns:
true if update serial even if object is unchanged
See Also:
updateObject(boolean)

isTxObject

public boolean isTxObject()
Determines whether this object becomes the txObject (see Db.setTxObject(org.tentackle.db.DbObject)) within a transaction. By default, only objects initiating a transaction are txObjects. However, for composites the top-level object usually is also the txObject, even if the transaction involves different txobjects. As a consequence, the current txObject can change during a transaction.

Returns:
true if this is a txObject.

initModification

public boolean initModification(char modType)
Does any preprocessing before delete, insert or update.

Parameters:
modType - is the modification type: DELETE, INSERT or UPDATE
Returns:
true if preprocessing ok, false if not

finishModification

public boolean finishModification(char modType)
Does any postprocessing after delete, insert or update.

Parameters:
modType - is the modification type: DELETE, INSERT or UPDATE
Returns:
true if postprocessing ok, false if not

finishNotUpdated

public boolean finishNotUpdated()
Does any update postprocessing for objects not being updated (because not modified for some reason, e.g. only composites modified). The default implementation does nothing. See AppDbObject.

Returns:
true if done, false if failed

beginTx

protected boolean beginTx(String txName)
Begins a transaction.
Also sets the txObject if a transaction is started or isTxObject() returns true.

Parameters:
txName - the transaction name
Returns:
true if tx begun

insertObject

public boolean insertObject(boolean withLinkedObjects)
Inserts this (new) object into the database.

Note: this method does *NOT* set the ID and should be used by the application with great care! Use save() instead!

Parameters:
withLinkedObjects - true if insert also linked objects
Returns:
true if done, false if duplicate

insert

public boolean insert()
Inserts this (new) object into the database with linked objects.

The modified attribute gets cleared if insert was successful. It is also verified that the object isSaveable().

Note: this method does *NOT* set the ID and should be used by the application with great care! Use save() instead!

Returns:
true if inserted, false if duplicate or not saveable.

updateObject

public boolean updateObject(boolean withLinkedObjects)
Updates this object to the database.
The modified attribute gets cleared if insert was successful. Note: this method should be used by the application with great care! Use save() instead!

Parameters:
withLinkedObjects - true if update also linked objects
Returns:
true if done, false if duplicate

update

public boolean update()
Updates this object to the database.
The modified attribute gets cleared if insert was successful. It is also verified that the object isSaveable().

Note: this method should be used by the application with great care! Use save() instead!

Returns:
true if done, false if duplicate or object is not saveable.

save

public boolean save()
Saves this object.
This is the standard method applications should use to insert or update objects.

If the ID is 0, a new ID is obtained and this object inserted. Otherwise this object is updated. The modified attribute gets cleared if save() was successful.

Returns:
true of done, false if duplicate

_save

public void _save()
           throws DbRuntimeException
Wrapper for save().

Unique violations and optimistic locking failures don't throw exceptions, because if these operations fail, the application can and must deal with it. However, in some situations (bulk operations) it is sufficient to just throw an exception instead.

Throws:
DbRuntimeException - thrown if save returned false

_delete

public void _delete()
             throws DbRuntimeException
Wrapper for delete().

Optimistic locking or delete failures don't throw exceptions, because if these operations fail, the application can and must deal with it. However, in some situations (bulk operations) it is sufficient to just throw an exception instead.

Throws:
DbRuntimeException - thrown if delete returned false

syncObject

public boolean syncObject(boolean withLinkedObjects)
Try to update an object first and if that failes, try to insert.
This method is used for transferring an Object from one DB to another as it is the case in RMI-connections, where the ID is transmitted, but the object may or may not exist in the other database. Notice that the modified-attribute remains unchanged!

Parameters:
withLinkedObjects - true if insert/update also linked objects
Returns:
true if done, false if failed

sync

public boolean sync()
Try to update an object first and if that failes, try to insert.
This method is used for transferring an Object from one DB to another as it is the case in RMI-connections, where the ID is transmitted, but the object may or may not exist in the other database. It is also verified that the object isSaveable().

Notice that the modified-attribute remains unchanged!

Returns:
true if done, false if failed

deleteObject

public boolean deleteObject(boolean withLinkedObjects)
Removes this object from the database.
Note: this method should be used by the application with great care! Use delete() instead!

Parameters:
withLinkedObjects - true if remove linked objects too.
Returns:
true if removed, false if no such object

delete

public boolean delete()
Removes this object from the database (with linked objects, i.e. standard-case). A removed object will also get the modified attribute set by definition, because it is isNew() again. It is also verified that the object isSaveable().

Returns:
true if removed, false if failed

markDeleted

public void markDeleted()
Marks an object to be deleted.
This is done by negating its id. If the object is already marked deleted the method does nothing. Must be overridden if the object is composite, i.e. all its composites must be markDeleted as well. Note: an object with a negative ID is always isModified().


countModification

public long countModification(boolean optimize)
Counts a modification for the class of this object.

Parameters:
optimize - is true if optimize modcounting within transaction
Returns:
the table serial if isTableSerialValid()==true, -1 if isCountModificationAllowed() == false
See Also:
ModificationCounter

countModification

public long countModification()
Counts a modification for the class of this object with optimization.

Returns:
the table serial if isTableSerialValid()==true, -1 if isCountModificationAllowed() == false
See Also:
ModificationCounter

selectModification

public long selectModification()
Selects the current modification counter for the class of this object.

Returns:
the modification counter
See Also:
ModificationCounter

selectExpiredTableSerials

public long[] selectExpiredTableSerials(long oldSerial)
Determines the objects with a tableSerial starting at a given serial. Useful to cleanup caches for example.

Parameters:
oldSerial - non-inclusive lower bound for tableSerial (>oldSerial)
Returns:
pairs of longs, the first being the ID, the second the tableserial, never null

selectExpiredTableSerials

public long[] selectExpiredTableSerials(long oldSerial,
                                        long maxSerial)
Determines the objects with their tableSerial within a given range. Useful to cleanup caches.

Parameters:
oldSerial - non-inclusive lower bound for tableSerial (> oldSerial)
maxSerial - inclusive upper bound for tableSerial (≤ maxSerial)
Returns:
pairs of longs, the first being the ID, the second the tableserial, never null

getExpirationBacklog

public long[] getExpirationBacklog(long minSerial,
                                   long maxSerial)
Gets the expiration backlog for a given range of tableserials. Note that the backlog is maintained only if DbGlobal.serverDb != null.

Parameters:
minSerial - the lower serial bound of the query (minSerial < tableSerial)
maxSerial - the upper serial bound of the query (tableSerial ≤ maxSerial)
Returns:
the expiration info as pairs of id/tableserial, null if given range was not found in the backlog

getExpiredTableSerials

public long[] getExpiredTableSerials(long oldSerial,
                                     long maxSerial)
Combines selectExpiredTableSerials(long) and getExpirationBacklog(long, long).
A physical database query is only done if the requested range is not in the backlog. Used in RMIservers to reduces db-roundtrips.

Parameters:
oldSerial - non-inclusive lower bound for tableSerial (> oldSerial)
maxSerial - inclusive upper bound for tableSerial (≤ maxSerial)
Returns:
pairs of longs, the first being the ID, the second the tableserial, never null

createModificationLog

public ModificationLog createModificationLog(char modType)
Creates a ModificationLog.

Parameters:
modType - is the modification type
Returns:
the created ModificationLog ready for save()

logModification

public boolean logModification(char modType)
Logs a modification for this object to the modlog (not to be mixed up with the modification-counter!)

Parameters:
modType - is the modification type (INSERT, DELETE or UPDATE)
Returns:
true if logging ok, false if writing the log failed

getRemoteDelegate

public DbObjectRemoteDelegate getRemoteDelegate()
Gets the delegate for remote connections.
Each class has its own delegate.

Returns:
the delegate for this object

getRemoteDelegateId

protected int getRemoteDelegateId()
Returns the ID of the delegate for the class of this object. The delegateId is unique for each class. It is valid only in remote connections and is the same for all remote Db's. The RMI-server creates a delegate for each subclass of DbObject.

Returns:
the delegate id
See Also:
DbObjectRemoteDelegateImpl

getFieldCount

public int getFieldCount()
Gets the number of columns (fields) in the table corresponding to the class of this object.
The method does a dummy select if not known so far.

Returns:
the number of columns

isGettingFieldCount

public boolean isGettingFieldCount()
As getFieldCount() is invoked from getFields(org.tentackle.db.ResultSetWrapper) this prevents a heap overflow.

Returns:
true if in getFieldCount

updateFieldCount

protected void updateFieldCount(int columnIndex)
Updates the fieldCount in the class variables if the given columnIndex is greater than current fieldcount.

Parameters:
columnIndex - is the result-set column index (>=1)

alwaysPrepare

public boolean alwaysPrepare()
Determines whether prepared statements of this class should always be prepared each time when the statement used.

Returns:
true if always prepare

setAlwaysPrepare

public void setAlwaysPrepare(boolean alwaysPrepare)
Sets the always prepare flag.

Parameters:
alwaysPrepare - true if always prepare

getSelectStatementId

protected int getSelectStatementId()
Gets the prepared statement id for select(long, boolean).

Returns:
the statement id

setSelectStatementId

protected void setSelectStatementId(int id)
Sets the prepared statement id for select(long, boolean).

Parameters:
id - the statement id

getSelectAllStatementId

protected int getSelectAllStatementId()
Gets the prepared statement id for selectAll(boolean).

Returns:
the statement id

setSelectAllStatementId

protected void setSelectAllStatementId(int id)
Sets the prepared statement id for selectAll(boolean).

Parameters:
id - the statement id

getSelectLockedStatementId

protected int getSelectLockedStatementId()
Gets the prepared statement id for selectLocked(long, boolean).

Returns:
the statement id

setSelectLockedStatementId

protected void setSelectLockedStatementId(int id)
Sets the prepared statement id for selectLocked(long, boolean).

Parameters:
id - the statement id

getSelectSerialStatementId

protected int getSelectSerialStatementId()
Gets the prepared statement id for selectSerial(long).

Returns:
the statement id

setSelectSerialStatementId

protected void setSelectSerialStatementId(int id)
Sets the prepared statement id for selectSerial(long).

Parameters:
id - the statement id

getInsertStatementId

protected int getInsertStatementId()
Gets the prepared statement id for insert().

Returns:
the statement id

setInsertStatementId

protected void setInsertStatementId(int id)
Sets the prepared statement id for insert().

Parameters:
id - the statement id

getUpdateStatementId

protected int getUpdateStatementId()
Gets the prepared statement id for update().

Returns:
the statement id

setUpdateStatementId

protected void setUpdateStatementId(int id)
Sets the prepared statement id for update().

Parameters:
id - the statement id

getDeleteStatementId

protected int getDeleteStatementId()
Gets the prepared statement id for delete().

Returns:
the statement id

setDeleteStatementId

protected void setDeleteStatementId(int id)
Sets the prepared statement id for delete().

Parameters:
id - the statement id

getDummyUpdateStatementId

protected int getDummyUpdateStatementId()
Gets the prepared statement id for dummyUpdate().

Returns:
the statement id

setDummyUpdateStatementId

protected void setDummyUpdateStatementId(int id)
Sets the prepared statement id for dummyUpdate().

Parameters:
id - the statement id

getUpdateSerialStatementId

protected int getUpdateSerialStatementId()
Gets the prepared statement id for updateSerial().

Returns:
the statement id

setUpdateSerialStatementId

protected void setUpdateSerialStatementId(int id)
Sets the prepared statement id for updateSerial().

Parameters:
id - the statement id

getUpdateTableSerialStatementId

protected int getUpdateTableSerialStatementId()
Gets the prepared statement id for updateTableSerial().

Returns:
the statement id

setUpdateTableSerialStatementId

protected void setUpdateTableSerialStatementId(int id)
Sets the prepared statement id for updateTableSerial().

Parameters:
id - the statement id

getUpdateSerialAndTableSerialStatementId

protected int getUpdateSerialAndTableSerialStatementId()
Gets the prepared statement id for updateSerialAndTableSerial().

Returns:
the statement id

setUpdateSerialAndTableSerialStatementId

protected void setUpdateSerialAndTableSerialStatementId(int id)
Sets the prepared statement id for updateSerialAndTableSerial().

Parameters:
id - the statement id

getSelectExpiredTableSerials1StatementId

protected int getSelectExpiredTableSerials1StatementId()
Gets the prepared statement id for selectExpiredTableSerials(long).

Returns:
the statement id

setSelectExpiredTableSerials1StatementId

protected void setSelectExpiredTableSerials1StatementId(int id)
Sets the prepared statement id for selectExpiredTableSerials(long).

Parameters:
id - the statement id

getSelectExpiredTableSerials2StatementId

protected int getSelectExpiredTableSerials2StatementId()
Gets the prepared statement id for selectExpiredTableSerials(long).

Returns:
the statement id

setSelectExpiredTableSerials2StatementId

protected void setSelectExpiredTableSerials2StatementId(int id)
Sets the prepared statement id for selectExpiredTableSerials(long).

Parameters:
id - the statement id

getTableName

public String getTableName()
Gets the database table name for the class of this object.

Returns:
the table name

getSingleName

public String getSingleName()
Gets the human readable name for one (1) object of this class.

Returns:
the name

getMultiName

public String getMultiName()
Gets the human readable name for multiple (> 1) objects of this class.

Returns:
the name

getFields

public abstract boolean getFields(ResultSetWrapper rs)
Retrieves the values of all fields (all columns of the database table) in the given ResultSetWrapper and stores them in the object's attributes.

Parameters:
rs - the result set
Returns:
true if all fields retrieved

prepareSetFields

public boolean prepareSetFields()
Prepares the object's attributes before the object is saved to the database. Should be overridden. The default implementation does nothing. Used to setup, check and align values.

Returns:
true if proceed with save/insert/update, false if some error.

setFields

public abstract int setFields(PreparedStatementWrapper st)
Sets the values of all fields (all columns of the database table) in the given PreparedStatementWrapper from the object's attributes.

Parameters:
st - the statement
Returns:
the number of fields set, -1 if error.

updateFields

public int updateFields(ResultSetWrapper rs)
Updates the fields in the result-set.
Because it is only used in updateable cursors and by far most apps don't use that feature, the method is not abstract and by default throws the exception for "not implemented".

Parameters:
rs - the result set
Returns:
the number of fields set, -1 if error.

getSqlAllFields

public String getSqlAllFields()
Gets the sql text to select all fields (and all objects).

Returns:
the sql text

getSqlSelectAllFields

public String getSqlSelectAllFields()
Get the SQL-string to select all columns of this class (may be across multiple tables)

Returns:
the sql-string for "SELECT * FROM ..."

prepareInsertStatement

public abstract int prepareInsertStatement()
Prepares the insert statement.

Returns:
the statememt id

prepareUpdateStatement

public abstract int prepareUpdateStatement()
Prepare the update statement.

Returns:
the statememt id

prepareSelectStatement

public int prepareSelectStatement()
Prepares the select statement (usually the same for all objects)

Returns:
the statememt id

prepareSelectLockedStatement

public int prepareSelectLockedStatement()
Prepares the select statement with lock (usually the same for all objects)

Returns:
the statememt id

prepareSelectSerialStatement

public int prepareSelectSerialStatement()
Prepares the selectSerial statement (usually the same for all objects)

Returns:
the statememt id

prepareDeleteStatement

public int prepareDeleteStatement()
Prepares the delete statement (usually the same for all objects)

Returns:
the statememt id

prepareDummyUpdateStatement

public int prepareDummyUpdateStatement()
Prepares the dummy update. Useful get an exclusive lock within a transaction

Returns:
the statememt id

prepareUpdateSerialStatement

public int prepareUpdateSerialStatement()
Prepares the serial update.

Returns:
the statememt id

prepareUpdateTableSerialStatement

public int prepareUpdateTableSerialStatement()
Prepares the tableSerial update.

Returns:
the statememt id

prepareUpdateSerialAndTableSerialStatement

public int prepareUpdateSerialAndTableSerialStatement()
Prepares the serial + tableSerial update.

Returns:
the statememt id

newByClass

public static <T extends DbObject> T newByClass(Class<T> clazz)
                                     throws InstantiationException,
                                            IllegalAccessException
Instantiates a new object for a given class (without db-context).

Type Parameters:
T - the class type
Parameters:
clazz - the class
Returns:
the object
Throws:
InstantiationException
IllegalAccessException

newByClassWrapped

public static <T extends DbObject> T newByClassWrapped(Class<T> clazz)
Instantiates a new object for a given class transforming exceptions to DbRuntimeException. Commonly used in apps to simplify code.

Type Parameters:
T - the class type
Parameters:
clazz - the class
Returns:
the object

newByClass

public static <T extends DbObject> T newByClass(Db db,
                                                Class<T> clazz)
                                     throws InstantiationException,
                                            IllegalAccessException
Instantiates a new object for a given class and db.

Type Parameters:
T - the class type
Parameters:
db - the db connection
clazz - the class
Returns:
the object
Throws:
InstantiationException
IllegalAccessException

select

public static <T extends DbObject> T select(Db db,
                                            Class<T> clazz,
                                            long id)
                                 throws InstantiationException,
                                        IllegalAccessException
Selects an object for a given class and db by its unique id.

Type Parameters:
T - the class type
Parameters:
db - the db connection
clazz - the class
id - the object ID
Returns:
the object or null if no such object.
Throws:
InstantiationException
IllegalAccessException

select

public static <T extends DbObject> T select(Db db,
                                            String className,
                                            long id)
                                 throws ClassNotFoundException,
                                        InstantiationException,
                                        IllegalAccessException
Selects an object for a given class name and db by its unique id.

Type Parameters:
T - the class type
Parameters:
db - the db connection
className - the class name
id - the object ID
Returns:
the object or null if no such object.
Throws:
ClassNotFoundException
InstantiationException
IllegalAccessException

selectAll

public static <T extends DbObject> List<T> selectAll(Db db,
                                                     Class<T> clazz)
                                          throws InstantiationException,
                                                 IllegalAccessException
Selects all objects of this class.

Type Parameters:
T - the database object class
Parameters:
db - the logical db connection
clazz - the database object class
Returns:
the list of objects
Throws:
InstantiationException
IllegalAccessException

deleteList

public static int deleteList(List<? extends DbObject> list)
Deletes a List of objects. Virgin objects are not deleted.

Parameters:
list - the list of object to delete
Returns:
the number of objects deleted, -1 if error (some object wasn't deleted)

markListDeleted

public static int markListDeleted(List<? extends DbObject> list)
Marks all objects in a list to be deleted.
Use this method if a list-SQL-delete removed a set of objects and you have to reflect that in the list of objects. Bulk-deletes with succeeding list-iteration for marking the objects deleted usually is faster that invoking deleteList().

Parameters:
list - the objects to delete
Returns:
the number of marked objects (with id > 0).

deleteMissingInList

public static int deleteMissingInList(List<? extends DbObject> oldList,
                                      List<? extends DbObject> newList)
Deletes all objects in oldList that are not in newList. The method is handy for deleting cascaded composite lists.

Parameters:
oldList - the list of objects stored in db
newList - the new list of objects
Returns:
the number of objects deleted, -1 if some error

isListModified

public static boolean isListModified(List<? extends DbObject> list)
Checks whether some of the objects in the list are modified. Useful for recursive optimizations.

Parameters:
list - the objects
Returns:
true if modified

saveList

public static int saveList(List<? extends DbObject> list,
                           boolean modifiedOnly)
Saves a list of DbObjects.
All objects with isSaveable() == true will be saved. If modifiedOnly is true only isModified() objects will be saved. All objects with isSaveable() == false and isNew() == false are removed! By definition, a TrackedArrayList must *NOT* contain untracked objects. The errorhandler will be invoked if such an object is detected. This is a quality measure to ensure code consistency. The wurblet DbRelations automatically takes care of that.

Parameters:
list - the list to save
modifiedOnly - is true if only modified objects are saved
Returns:
the number of objects saved, -1 if some error

saveList

public static int saveList(List<? extends DbObject> list)
Saves a list of objects.
The linked objects are saved as well. All objects with isSaveable() == true will be saved. If modifiedOnly is true only isModified() objects will be saved. All objects with isSaveable() == false and isNew() == false are removed! By definition, a TrackedArrayList must *NOT* contain untracked objects. The errorhandler will be invoked if such an object is detected. This is a quality measure to ensure code consistency. The wurblet DbRelations automatically takes care of that.

Parameters:
list - the list to save
Returns:
the number of objects saved, -1 if some error


Copyright © 2001-2008 Harald Krake, Bergstr. 48, 78098 Triberg, Germany, harald@krake.de