From 9.0.3 onwards, this class is no longer used to represent a connected transaction. The connected state, by default, is now represented by DBTransactionImpl2. Applications using custom DBTransactionImpl and/or NullDBTransactionImpl subclass(es) should now subclass DBTransactionImpl2 instead.

Applications requiring backward compatibility must set the jbo.server.useNullDbTransaction property to true in appmodule configuration, initial context environment or as a System property to continue using this class as the default implementation for representing connected DBTransaction.

Using Anonymous View Objects

The DBTransactionImpl class has these methods for creating View Objects:

createViewObject

creatViewObjectFromQueryClauses

createViewObjectFromQueryName

In contrast to the "create View Object" methods on the ApplicationModuleImpl class, the methods on DBTransaction do not take a String voNname parameter. These methods create anonymous View Objects on the database transaction. Anonymous View Objects do not require an Application Module. An anonymous View Object is a View Object to which you do not give a name and that is usually used locally. For example, you could use an anonymous View Object when you want to perform a query (for example, a look-up) through a View Object, then remove it.

Anonymous View Objects should not be passed around between Application Modules. As soon as the anonymous View Object has performed its task, it should be discarded with the View Object remove() method.

Using anonymous View Objects also lets you avoid name clashes between View Objects. For example, if one Entity Object developer builds some code that is expecting to create a View Object in its own Application Module with a name like "temp" and another unrelated Entity Object developer builds some code that is expecting to work with a View Object in its own Application Module named "temp" (but which is for a totally different View Object), then if an application required both of these Application Modules to works as peers, name clashes could result.

The method getDBTransaction().createViewObject() creates a View Object from a definition created at design time which can be based on Entity Objects just like the ones you might have been creating with the createViewObject from the ApplicationModule class.

The DBTransactionImpl class also has createViewObjectFromQueryStmt and createViewObjectFromQueryClauses just like the Application Module class does; all of the same functionality is available to the Entity Object business logic writer.

The only difference is that the DBTransactionImpl class approach forces the Entity Object business logic writer to not pre-select an "instance" name for the View Object being used (the equivalent of calling the Application Module-level methods with a null instance name argument) so that the system ensures the "instance" names are unique and no unintended clashes occur.

To illustrate the differences between using the create View Object methods on the Application Module class versus the DBTransaction class, consider the following code snippets. Assume you have a method called doSomething() on an Entity Object to implement some operation. Two possible implementations are:

Implementations 1 and 2 are both correct approaches. Creating a nested Application Module is good for multi-View Object data models, and DbTransaction is good for simple one-off queries. If your application is using one-off queries most of the time, you might find that the extra overhead of creating an Application Module "container" might not add sufficient value.

DBTransactionImpl(java.lang.String url)Deprecated.Since 9.0.3. This constructor is no longer called to create a connected DBTransaction instance. Instead, DBTransactionImpl2 instance, created by create(), migrates from disconnected to connected state.

DBTransactionImpl(java.lang.String url, java.util.Properties info)Deprecated.Since 9.0.3. This constructor is no longer called to create a connected DBTransaction instance. Instead, DBTransactionImpl2 instance, created by create(), migrates from disconnected to connected state.

DBTransactionImpl(java.lang.String url, java.lang.String user, java.lang.String password)Deprecated.Since 9.0.3. This constructor is no longer called to create a connected DBTransaction instance. Instead, DBTransactionImpl2 instance, created by create(), migrates from disconnected to connected state.

DBTransactionImpl(java.lang.String url, java.lang.String user, java.lang.String password, java.util.Properties info)Deprecated.Since 9.0.3. This constructor is no longer called to create a connected DBTransaction instance. Instead, DBTransactionImpl2 instance, created by create(), migrates from disconnected to connected state.

connectToDataSource(java.util.Hashtable env, java.lang.String dsName, boolean isJTABased)
Looks up a datasource from a jndi tree and acquires the jdbc connection from the looked up datasource using the javax.sql.Datasource.getConnection(String user, String passwd) method.

void

connectToDataSource(java.util.Hashtable env, java.lang.String dsName, java.lang.String user, java.lang.String passwd, boolean isJTABased)
Looks up a datasource from a jndi tree and acquires the jdbc connection from the looked up datasource using the javax.sql.Datasource.getConnection(String user, String passwd) method.

void

connectToDataSource(java.lang.String nsUrl, java.lang.String nsUser, java.lang.String nsPasswd, java.lang.String dsUrl)
Looks up a datasource from Oracle 8i namespace using the jdbc_access protocol and acquires the default jdbc connection from the looked up datasource using the javax.sql.Datasource.getConnection() method.

getBatchPostExceptionThreshold()
In case of batch mode post operation, try to post the batched set of entities for each entity type and post operation (Insert/Update/Delete) for this many number of exceptions.

setBatchPostExceptionThreshold(int count)
Set this value to 0 to let all the modified entities be posted for each entity type and entity-DML operation to collect possible exceptions for all such entities.

DBTransactionImpl

DBTransactionImpl

Creates an instance from an existing JDBC connection. This constructor is used when applications supply their own JDBC connection to an Application Module's transaction.

Parameters:

connection - an existing connection.

DBTransactionImpl

public DBTransactionImpl(java.lang.String url)

Deprecated.Since 9.0.3. This constructor is no longer called to create a connected DBTransaction instance. Instead, DBTransactionImpl2 instance, created by create(), migrates from disconnected to connected state.

Attempts to establish a connection to a database through the given URL. The driver manager attempts to select an appropriate driver from the set of registered JDBC drivers.

DBTransactionImpl

Deprecated.Since 9.0.3. This constructor is no longer called to create a connected DBTransaction instance. Instead, DBTransactionImpl2 instance, created by create(), migrates from disconnected to connected state.

Attempts to establish a connection to a database through the given URL. The driver manager attempts to select an appropriate driver from the set of registered JDBC drivers.

Parameters:

url - a database URL of the form JDBC:subprotocol:subname.

info - a list of arbitrary string tag/value pairs as connection arguments; normally at least "user" and "password" tags should be included.

DBTransactionImpl

Deprecated.Since 9.0.3. This constructor is no longer called to create a connected DBTransaction instance. Instead, DBTransactionImpl2 instance, created by create(), migrates from disconnected to connected state.

Attempts to establish a connection to a database through the given URL. The driver manager attempts to select an appropriate driver from the set of registered JDBC drivers.

Parameters:

url - a database URL of the form JDBC:subprotocol:subname.

user - the database user on whose behalf the connection is being made.

DBTransactionImpl

Deprecated.Since 9.0.3. This constructor is no longer called to create a connected DBTransaction instance. Instead, DBTransactionImpl2 instance, created by create(), migrates from disconnected to connected state.

Internal:Applications should not use this constructor.

Attempts to establish a connection to the given database URL. The DriverManager attempts to select an appropriate driver from the set of registered JDBC drivers.

Parameters:

url - a database url of the form jdbc:subprotocol:subname

user - the database user on whose behalf the Connection is being made

password - the user's password

info - a list of arbitrary string tag/value pairs as connection arguments; normally at least a "user" and "password" property should be included

closeTransaction

public void closeTransaction()

Internal:Applications should not use this method.

Closes this transaction's JDBC connection.

Performs rollback on the current transaction to reset all the data in the cache to their initial states and then drops the JDBC connection. This method is invoked by disconnect to terminate the JDBC connection. Applications should use disconnect() instead of closeTransaction() to properly release JDBC resources.

setBundledExceptionMode

Set this transaction into bundled exception mode. In this mode, all exceptions thrown during updates to rows will be cached by the entity-cache. However when the rows are validated either by explicit validation call or when the transaction is committed, these exceptions will be thrown bundled in a RowValException. When in bundledException mode, validation code in setXXX methods on the Entity will be executed and if a ValidationException is thrown from these methods, they're cached by the Entity and thrown later as a detail of RowValException when the Entity is eventually validated.

isClearCacheOnCommit

public boolean isClearCacheOnCommit()

Returns the flag indicating whether all Entity Object caches will be cleared after the transaction is committed.

After the transaction is committed, the value of this flag is used to determine whether the Entity Object caches are cleared or not. If this flag value is false, the cache contents are kept. In this case, the cache may contain data that is stale in that it does not match the newest data (changes made by another user and committed).

If this flag is true, the caches are cleared after the transaction is committed. When the user brings in data by traversing row collection, the latest data from the database will be brought into Entity caches.

setClearCacheOnCommit

public void setClearCacheOnCommit(boolean val)

Sets the value of the flag indicating whether all Entity Object caches will be cleared after the transaction is committed.

The initial value of this flag is retrieved from the Application Module definition of the root Application Module (an XML attribute value named "ClearCacheOnCommit" in the Application Module definition's XML file). If the Application Module definition does not contain the initial value, the default value is false, i.e., the caches are kept after commit.

The user can override the value of this flag for this Transaction by calling this method. Calling this method does not affect the initial value in the Application Module definition.

isClearCacheOnRollback

public boolean isClearCacheOnRollback()

Returns the flag indicating whether all Entity Object caches will be cleared after the transaction is rolled back.

After the transaction is rolled back, the value of this flag is used to determine whether the Entity Object caches are cleared or not. If this flag value is false, the cache contents are kept. In this case, the cache may contain data that is not in sync with database in that uncommitted changes made this by user (before the transaction was rolled back) will be kept.

If this flag is true, the caches are cleared after the transaction is rolled back. When the user brings in data by traversing row collection, the latest data from the database will be brought into Entity caches.

setClearCacheOnRollback

public void setClearCacheOnRollback(boolean val)

Sets the value of the flag indicating whether all Entity Object caches will be cleared after the transaction is rolled back.

The initial value of this flag is retrieved from the Application Module definition of the root Application Module (an XML attribute value named "ClearCacheOnRollback" in the Application Module definition's XML file). If the Application Module definition does not contain the initial value, the default value is true, i.e., the caches are cleared after rollback.

The user can override the value of this flag for this Transaction by calling this method. Calling this method does not affect the initial value in the Application Module definition.

doValidatePostChanges

invoke validate() and postChanges() iteratively based on validateThreshold and postThreshold setting.

doBeforeCommit

public void doBeforeCommit()

doAfterCommit

public void doAfterCommit()

commit

public void commit()

Commits all changes in this transaction to the database, making them visible to other users and transactions. This method is called on the Application Module's transaction. For example:

appMod.getTransaction().commit();

When the commit process begins multiple attempts are made to validate all objects in the list of validation listeners, depending on the setting of the validation threshold. After each attempt, top-level entities that are still invalid will remain in the list. If any remain after the last attempt, a failure exception is thrown.

Each listed TransactionPostListener is notified to post any changes to the database using the postChanges method. Non-transient listeners are notified first, followed by transient listeners. The post phase is repeated, the number of repetitions depending on the setting of the validation threshold. If any invalid objects remain after the last repetition, a failure exception is thrown.

Following validation, no further changes to data should be made until the commit operation is completed.

Finally, beforeCommit events are posted to the listeners, the data is committed, afterCommit events are posted, and transient listeners are deleted from the transaction. For both beforeCommit and afterCommit events, non-transient listeners preceed transient listeners.

Note, if your Application Module is an EJB session bean, a new transaction is started for you automatically after calling commit. You do not have to explicitly start a new transaction.

commitAndSaveChangeSet

Commits the transaction and writes updated EntityImpls to the persistent store.

This method (along with applyChangeSet and removeChangeSet is used to synchronize the cache between root Application Module instances in an Application Module pool.

commitAndSaveChangeSet commits the transaction, but during the commit process, writes out "changed" EntityImpls to the persistent store. These changes are stored as a "change set". The change set can then be applied to other transactions (that is, to the Entity caches of other root Application Modules).

The integer value returned by this method identifies the change set that is stored in persistent store.

To apply the changes to another transaction (or Application Module cache), call Transaction.applyChangeSet(int) where int is the integer value returned by commitAndSaveChangeSet that represents the change set.

For example, assume you have two root Application Modules, named am1 and am2, in an Application Module pool.

// The line below commits the transaction in am1 and writes the change
// set to persistent store (database table). The returning snapId
// identifies the (persistent) change set.
int snapId = am1.getTransaction().commitAndSaveChangeSet();
// Use that change set and apply the changes to the other Application
// Module, am2. That is, apply changes from am1 to am2.
am2.getTransaction().applyChangeSet(snapId);
// When you are done with the change set, remove (free) it.
am1.getTransaction().removeChangeSet(snapId);

rollback

public void rollback()

Discards all modifications made in this transaction. This method is called on the Application Module's transaction. For example:

appMod.getTransaction().rollback();

When this method is invoked, beforeRollback events are posted to the listeners, the changes are discarded, afterRollback events are posted, and transient listeners are deleted from the transaction. For both events, non-transient listeners preceed transient listeners.

In the following example, a method named updateAttr has been implemented to update a row of a View Object vo with the value newAttrVal. If updateAttr succeeds (returns true), the code commits the transaction; otherwise, it rolls the transaction back:

postChanges

public void postChanges()

Synchronizes the changes in the middle-tier transaction-cache with the database.

This method bypasses the validation cycle and can allow invalid data to be posted to the database. As a side effect of this method, database triggers or other constraints might be fired as a result of posting data. However, invalid changes cannot be committed, as the commit() method validates all changes before committing them.

Typically, applications should call this method if they must execute SQL operations or queries with the current cached-state of data, before validating the changes.

setBatchModeForEntity

Sets the updatebatching (Batch post operations) mode on or off for a given entity type in this transaction.

Parameters:

def - - Def for the desired entity type

mode - - whether to turn batch updates on or off. if false rest of the arguments are ignored. If attribute list is null or has no elements, then Def is consulted for any default setting in the def for AttributeLists for these purposes. If Def does not have an attribute list then ALL attributes participate in the concerned operation.

postChanges

Synchronizes all the changes in this transaction-cache with the database. These changes are still not visible to other users/transaction.

Executes a savepoint before starting to post any changes. Then, all non-transient and transient TransactionPostListeners are notified to post their changes, in that order. In case of any exception, rollsback the transaction to the savepoint. and throws DMLException.

For Entity types that are marked to use batch update in case of oracle jdbc, first a maximal-attribute-changed-set is collected for each entity-type so that batch statements could be created for all changes. Then postChanges() is called on all the entities in the transaction just like in the normal case, but entity does not execute the dml, instead simply adds the DML to a batched statement which is executed after all entities are done adding their changes to the batch. Then for each entity type that has batched statements executes the batches (deletes first, followed by inserts and then updates). On any eror during the batch operations, the entire transaction is rolled back to the savepoint as described earlier.

hasRollbackSavePoint

protected boolean hasRollbackSavePoint()

createStatement

Applications may use this method to create a JDBC statement object to execute application specific SQL statements directly, so that the modifications are committed to the database in a single transaction through this object.

createCallableStatement

Applications may use this method to create a JDBC callable statement object to execute application-specific SQL statements directly, so that the modifications are committed to the database in a single transaction through this object.

createPreparedStatement

Applications may use this method to create a JDBC callable statement object to execute application specific SQL statements directly, so that the modifications are committed to the database in a single transaction through this object.

noRowsPrefetch - the number of rows to prefetch when executing this statement's query. If this parameter is set to DBTransaction.DEFAULT, then the default value from the jdbc driver is used.

Returns:

a JDBC PreparedStatement instance.

executeCommand

public int executeCommand(java.lang.String command)

Executes a SQL command using a JDBC Statement under the current transaction. Applications should use this method to execute application-specific JDBC statements.

This method provides a way of bypassing the framework to query the database directly. Internally, the method passes the specified SQL command to a statement on the JDBC connection and executes it.

The following code example uses executeCommand. The SQL string is designed to update the EMP table. This example passes the string to executeCommand, then prints a message to report how many rows were actually updated.

dumpQueryResult

Writes the result of the query to a (potentially very long) string. It takes three parameters: the first is the SQL query statement. The second is the class that dumps the result to a string. This class must implement the oracle.jbo.server.QueryDump interface. The implementation of this class decides what to do with the third, data parameter (which can be null). This is a utility method for testing and debugging queries and applications.

lookupEntityCache

findEntityCache

Finds a Cache table for the entity. This method will find the internal EntityCache object which is allocated to cache the Entity information. If one is not already present for the type of Entity, then it will be created and returned.

putTransAttrValEntry

validate

public void validate()

Starts the validation cycle and validates all subscribers in the ValidationListener list. Typically all top-level entities which were invalidated through the framework will be in this list. Listeners are removed as they are validated.

The advantage of calling validate() is that the data stays in the middle tier. Data is not posted to the database, thus avoiding the possible firing of database triggers or constraints.

setValidationThreshold

When commit() is invoked the framework attempts to validate the transaction's modifications, making count attempts before failing with an exception. This mechanism allows applications to update data in the cache within the validation phase, and validate them before they are posted.

setPostThreshold

When commit() is invoked the framework attempts to post the transaction's modifications, making count attempts before failing with an exception. This mechanism allows applications to update data in the cache within the post phase, and commit all changes.

setBatchPostExceptionThreshold

public void setBatchPostExceptionThreshold(int count)

Set this value to 0 to let all the modified entities be posted for each entity type and entity-DML operation to collect possible exceptions for all such entities. Set this number to a postive integer to set a limit on number of exceptions to collect for each entity type and DML operation before aborting the post operation.

isDirty

public boolean isDirty()

This method is typically called before an attempt is made to post the data. For example, this method can be called when the user at the client attempts to close an application. If there is unsaved data, this method can return true. In response, the client can prompt the user to save before closing the application.

trueif any data within this Application Module has been modified but not yet committed; false otherwise.

dumpEntityCaches

public void dumpEntityCaches(java.io.Writer out)

Iterates over the currently populated caches of entities, and write a representation of them to a charater stream. Internal:Applications should not use this method.

showCursorUsage

public void showCursorUsage(java.io.Writer out)

Internal:Applications should not use this method.

doCommit

protected void doCommit()

Called by the commit method to issue the commit call. This method is called just before the transaction is committed on the JDBC connection. Override this method to provide your own handler for the commit operation.

doRollback

protected void doRollback()

Called by the rollback method to issue the rollback call. This method is called just before the transaction is rolled back on the JDBC connection. Override this method to provide your own handler for the rollback operation.

connect

public void connect(java.sql.Connection sqlConnection)

Deprecated.

Uses this JDBC Connection object to connect to the database for all operations via this transaction. ApplicationModule calls this method on the transaction object. Internal:Applications should not use this method.

connect

public void connect(java.lang.String url)

Uses this JDBC Connection object to connect to the database for all operations via this transaction. ApplicationModule calls this method on the transaction object. Internal:Applications should not use this method.

connectToDataSource

Looks up a datasource from Oracle 8i namespace using the jdbc_access protocol and acquires the default jdbc connection from the looked up datasource using the javax.sql.Datasource.getConnection() method.

dsUrl - Datasource name as bound in the namespace. Name can be the fully qaultified url such as jdbc_access://test/ds/db1 otherwise the the url prefix jdbc_acess:// is prepended to the datasource name for lookup.

Looks up a datasource from Oracle 8i namespace using the jdbc_access protocol and acquires the jdbc connection from the looked up datasource using the javax.sql.Datasource.getConnection(String user, String password) method.

dsUrl - Datasource name as bound in the namespace. Name can be the fully qaultified url such as jdbc_access://test/ds/db1 otherwise the the url prefix jdbc_acess:// is prepended to the datasource name for lookup.

user - Username for which the connection is acquired from the datasource

disconnect

public void disconnect(boolean retainState)

Closes the JDBC connection object. If disconnect is invoked with retainState equal to false then the JDBC connection will be closed and this transaction will be removed* from the root application module.

If disconnect is invoked with retainState equal to true then this transaction's JDBC connection will be closed but, the root application module will continue to reference this transaction and its state. The transaction state may include unposted database changes and cached result sets. In the middle tier, reconnect on the DBTransaction interface may be invoked to re-establish a JDBC connection for this transaction. If connection pooling is enabled for this middle tier instance this connection may represent a recycled connection.

The developer should take measures to ensure that the following requirements are met before attempting to disconnect a JDBC connection and retain application module state. All of these validations are not currently performed by the disconnection implementation because of performance considerations:

All non-forward only view objects should have fetched in all data

If pessimistic locking is enabled, all pending changes should be commited/rolled back.

All changes that have been posted to the database should be commited/rolled back>/p>

reconnect

public void reconnect()

Reconnect the ApplicationModule to the database, using previously supplied database credentials. This method should only be invoked if the transaction has been previously disconnected using disconnect(boolean) with the retainState parameter equal to true or, if a previous isConnected() request had discovered a stale JDBC connection. If it is invoked otherwise the method will do nothing.

reconnect

public void reconnect(boolean force)

Reconnect the Application Module to the database, if necessary, using previously supplied database credentials. If the parameter is true, then a database disconnect and reconnect is performed, whatever the current connection state. If false, the connect is only performed if the connection has disappeared.

findByPrimaryKey

Finds an Entity Object in this transaction given an EntityDef object and a Primary Key.

Given the EntityDef object and the table's primary key, this method returns the associated Entity Object. If the Entity has not already been brought into the cache by any of the View Objects, this method will cause the Entity to be fetched from the database. This method returns null if the Entity Object is not found.

For example, use this method to create a set of Entity Objects based on a relational schema without the need to create any Application Modules or View Objects. To do this, use findByPrimaryKey to locate a specific object and then traverse association accessors to get to all the other objects.

findByPrimaryKey

Finds an Entity Object in this transaction given the String name of the EntityDef and a Primary Key.

Given the String name of the EntityDef and the table's primary key, this method returns the associated Entity Object. If the Entity has not already been brought into the cache by any of the View Objects, this method will cause the Entity to be fetched from the database.

This method returns null if the Entity Object is not found.

For example, use this method to create a set of Entity Objects based on a relational schema without the need to create any Application Modules or View Objects. To do this, use findByPrimaryKey to locate a specific object and then traverse association accessors to get to all the other objects.

createViewObjectFromQueryStmt

Creates an anonymous query definition from an SQL statement. The returned ViewObject is an instance of the Class name that is passed in as the argument. This allows for custom logic in a subclass of the framework provided oracle.jbo.server.ViewObjectImpl class.

findViewObject

Find a view object with the specified name. The name passed in the argument should either be relative to the root Application Module of the transaction or a fully-qualified path when nested Application Modules are involved.

createApplicationModule

Creates an anonymous Application Module. This method is useful for Entity Object middle-tier routines or for creating a sandbox for a service or utility object. With this method, View Objects can be created within the "scope" of that Application Module; then the application module can be passed around. The code in the Application Module can, for example, make assumptions about what View Objects are available and contain code for customizing them. It can control the namespace of objects that are contained within it. For example, the Entity Object middle-tier routine can call:

getDbTransaction().createApplicationModule()

then use that Application Module as its local scratchpad. The routine can pass that Application Module around to others. The anonymous Application Module provides a temporary namespace and can be discarded with one .remove() call to clean-up just the things that the Entity Object needed temporarily.

setDMLOperationTimeOut

Sets the query time out value for the Entity Object's DML operations. The default is DML_OPERATION_TIMEOUT_WAIT_FOREVER (-1), which means that the DML operations will not time out. The user will be able to cancel the long running operations by calling cancelDMLOperations() started by this Transaction during postChanges.

If a positive value of timeout is specified the operation is monitored by a global monitor thread. The monitor thread waits the specified amount of time (approximately) in milli-seconds, and cancels the operation by calling JDBC's Statement.cancel().