Oracle ADF Model and Business Components API Reference 10.1.2 B14022-01

oracle.jbo
Interface Transaction

All Known Subinterfaces:
DBTransaction
All Known Implementing Classes:
ApplicationModuleImpl, DBTransactionImpl, NullDBTransactionImpl

public interface Transaction

Provides the base methods for defining database transactions.

Since:
JDeveloper 3.0

Field Summary
static int LOCK_NONE
          Indicates that the row locking mode is Manual.
static int LOCK_OPTIMISTIC
          Indicates that the row locking mode is Automatic and Optimistic.
static int LOCK_OPTUPDATE
          Indicates that the row locking mode is Automatic and uses Optimistic Update.
static int LOCK_PESSIMISTIC
          Indicates that the row locking mode is Automatic and Pessimistic.
 
Method Summary
 void addTransactionStateListener(TransactionStateListener target)
           
 void addViewClearCacheListener(ViewClearCacheListener target)
           
 void applyChangeSet(int id)
          Applies the changes committed by another transaction in order to synchronize caches between root Application Module instances.
 void clearEntityCache(java.lang.String entityName)
          Clears the cache of the specified Entity Object.
 void commit()
          Commits all changes in this transaction to the database, making them visible to other users and transactions.
 int commitAndSaveChangeSet()
          Commits the transaction and writes updated EntityImpls to the persistent store.
 void connect(java.lang.String url)
          Attempts to establish a connection to a database identified by a URL.
 void connect(java.lang.String url, java.util.Properties info)
          Attempts to establish a connection to a database identified by a URL.
 void connect(java.lang.String url, java.lang.String user, java.lang.String password)
          Attempts to establish a connection to a database identified by a URL.
 void connectToDataSource(java.util.Hashtable initialContextEnv, java.lang.String dataSourceName, boolean isXABased)
          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 initialContextEnv, java.lang.String dataSourceName, java.lang.String user, java.lang.String password, boolean isXABased)
          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 dataSourceName)
          Deprecated. Since Jdeveloper 9.0.2. No replacement
 void connectToDataSource(java.lang.String nsUrl, java.lang.String nsUser, java.lang.String nsPasswd, java.lang.String dataSourceName, java.lang.String user, java.lang.String password)
          Deprecated. Since Jdeveloper 9.0.2. No replacement
 java.lang.Object createRef(java.lang.String structName, byte[] data)
          Internal: Applications should not use this method.
 void disconnect()
          Closes the JDBC connection object and removes this transaction from the root application module.
 void disconnect(boolean retainState)
          Closes the JDBC connection object.
 java.lang.String dumpQueryResult(java.lang.String query, java.lang.String dumpClassName, java.lang.String[] data)
          Writes the result of the query to a (potentially very long) string.
 int executeCommand(java.lang.String command)
          Executes a SQL command using a JDBC Statement under the current transaction.
 ConnectionMetadata getConnectionMetadata()
          Returns a metdata structure that describes the transaction's JDBC connection.
 int getLockingMode()
          Returns the preferred locking mode for this Transaction.
 boolean isBundledExceptionMode()
           
 boolean isClearCacheOnCommit()
          Returns the flag indicating whether all Entity Object caches will be cleared after the transaction is committed.
 boolean isClearCacheOnRollback()
          Returns the flag indicating whether all Entity Object caches will be cleared after the transaction is rolled back.
 boolean isConnected()
          Checks if the transaction is connected to the database.
 boolean isDirty()
          Checks if any data within this Application Module has been modified but not yet committed.
 void postChanges()
          Synchronizes the changes in the middle-tier transaction-cache with the database.
 void reconnect()
          Re-establish the transaction JDBC connection using previously supplied database credentials.
 void reconnect(boolean force)
          Deprecated. Deprecated since 3.2. Instead, use reconnect().
 void removeChangeSet(int id)
          Removes the change set that defines the changes to EntityImpls within a transaction.
 void removeTransactionStateListener(TransactionStateListener target)
           
 void removeViewClearCacheListener(ViewClearCacheListener target)
           
 void rollback()
          Discards all modifications made in this transaction.
 void setBundledExceptionMode(boolean flag)
          Set this transaction into bundled exception mode.
 void setClearCacheOnCommit(boolean val)
          Sets the value of the flag indicating whether all Entity Object caches will be cleared after the transaction is committed.
 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.
 void setLockingMode(int mode)
          Sets the preferred locking mode for this Transaction.
 void validate()
          Starts the validation cycle and validates all subscribers in the ValidationListener list.
 

Field Detail

LOCK_NONE

public static final int LOCK_NONE
Indicates that the row locking mode is Manual.

See Also:
Constant Field Values

LOCK_PESSIMISTIC

public static final int LOCK_PESSIMISTIC
Indicates that the row locking mode is Automatic and Pessimistic.

See Also:
Constant Field Values

LOCK_OPTIMISTIC

public static final int LOCK_OPTIMISTIC
Indicates that the row locking mode is Automatic and Optimistic.

See Also:
Constant Field Values

LOCK_OPTUPDATE

public static final int LOCK_OPTUPDATE
Indicates that the row locking mode is Automatic and uses Optimistic Update.

See Also:
Constant Field Values
Method Detail

connect

public void connect(java.lang.String url)
Attempts to establish a connection to a database identified by a URL.

The DriverManager attempts to select an appropriate driver from the set of registered JDBC drivers.

Call isConnected to see if the connection was successful.

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

connect

public void connect(java.lang.String url,
                    java.util.Properties info)
Attempts to establish a connection to a database identified by a URL.

The DriverManager attempts to select an appropriate driver from the set of registered JDBC drivers.

Call isConnected to see if the connection was successful.

Parameters:
url - a database url of the form jdbc:subprotocol:subname.
info - a list of arbitrary string tag/value pairs to be used as connection arguments. Normally, at least "user" and "password" properties should be included.

connect

public void connect(java.lang.String url,
                    java.lang.String user,
                    java.lang.String password)
Attempts to establish a connection to a database identified by a URL.

The DriverManager attempts to select an appropriate driver from the set of registered JDBC drivers.

Call isConnected to see if the connection was successful.

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.

connectToDataSource

public void connectToDataSource(java.lang.String nsUrl,
                                java.lang.String nsUser,
                                java.lang.String nsPasswd,
                                java.lang.String dataSourceName)
Deprecated. Since Jdeveloper 9.0.2. No replacement

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.

Parameters:
nsUrl - Url to the jndi namespace where the datasource is bound
nsUser - User name that is used to access the namespace.
nsPasswd - nsUsers' passwd

connectToDataSource

public void connectToDataSource(java.lang.String nsUrl,
                                java.lang.String nsUser,
                                java.lang.String nsPasswd,
                                java.lang.String dataSourceName,
                                java.lang.String user,
                                java.lang.String password)
Deprecated. Since Jdeveloper 9.0.2. No replacement

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.

Parameters:
nsUrl - Url to the jndi namespace where the datasource is bound
nsUser - User name that is used to access the namespace.
nsPasswd - nsUsers' passwd
user - Username for which the connection is acquired from the datasource
password - User's password.

connectToDataSource

public void connectToDataSource(java.util.Hashtable initialContextEnv,
                                java.lang.String dataSourceName,
                                java.lang.String user,
                                java.lang.String password,
                                boolean isXABased)
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.

Parameters:
initialContextEnv - Envirionment used the create initial context. May be null.
user - Username for which the connection is acquired from the datasource
password - User's password.
isXABased - True if datasource is XADataSource implementation. If true, the tranasction is assumed to be controlled by an external transaction manager.

connectToDataSource

public void connectToDataSource(java.util.Hashtable initialContextEnv,
                                java.lang.String dataSourceName,
                                boolean isXABased)
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.

Parameters:
initialContextEnv - Envirionment used the create initial context. May be null.
isXABased - True if datasource is XADataSource implementation. If true, the tranasction is assumed to be controlled by an external transaction manager.

reconnect

public void reconnect()
Re-establish the transaction JDBC connection using previously supplied database credentials.

If the application module was previously disconnected using disconnect(true) (retain application module state) then this method should only re-establish the transaction JDBC connection.

If the application module was previously disconnected using disconnect(false) (do not retain application module state) then this method should re-establish the transaction JDBC connection and reset the application module non-transactional state which may include child view usage and application module usage instances.


reconnect

public void reconnect(boolean force)
Deprecated. Deprecated since 3.2. Instead, use reconnect().

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.

Parameters:
force - force a reconnect, should usually be false.

disconnect

public void disconnect()
Closes the JDBC connection object and removes this transaction from the root application module.

Throws:
NotConnectedException - if the jdbc connection wasn't acquired

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.

Throws:
NotConnectedException - if the jdbc connection wasn't acquired

isConnected

public boolean isConnected()
Checks if the transaction is connected to the database. In a three-tier scenario, clients can call this method to check if the middle tier is connected to the database.

Returns:
true if connected; false if disconnected.

setLockingMode

public void setLockingMode(int mode)
Sets the preferred locking mode for this Transaction. The possible values are:

Changing the locking mode affects only subsequent locks. Current locks are not affected.

Parameters:
mode - one of LOCK_PESSIMISTIC, LOCK_OPTIMISTIC or LOCK_NONE.

getLockingMode

public int getLockingMode()
Returns the preferred locking mode for this Transaction. For example:

 am.getTransaction().getLockingMode();
 
The possible return values are:

If not set by setLockingMode, the locking mode defaults to LOCK_PESSIMISTIC.

Returns:
an integer representing the preferred locking mode. The values can be LOCK_NONE, LOCK_PESSIMISTIC (default), or LOCK_OPTIMISTIC.

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.

Parameters:
val - the new value of the clear-cache-on-commit flag. true indicates that the Entity Object caches will be cleared after commit.
See Also:
isClearCacheOnCommit()

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.

Returns:
the current value of clear-cache-on-commit flag.
See Also:
RowSet.executeQuery(), setClearCacheOnCommit(boolean val)

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.

Parameters:
val - the new value of the clear-cache-on-roll-back flag. true indicates that the Entity Object caches will be cleared after rollback, and will be refreshed with new data from the database.
See Also:
isClearCacheOnRollback()

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.

Returns:
the current value of clear-cache-on-roll-back flag.
See Also:
RowSet.executeQuery(), setClearCacheOnRollback(boolean val)

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.


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.

See Also:
commit()

isDirty

public boolean isDirty()
Checks if any data within this Application Module has been modified but not yet committed. 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.

Returns:
true if the local data and the database differ.

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.

See Also:
TransactionListener.beforeCommit(TransactionEvent), TransactionListener.afterCommit(TransactionEvent), DBTransaction, postChanges()

commitAndSaveChangeSet

public int 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 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);
 

Returns:
an integer representing an EntityImpl change set in persistent store.
See Also:
applyChangeSet(int), removeChangeSet(int)

applyChangeSet

public void applyChangeSet(int id)
Applies the changes committed by another transaction in order to synchronize caches between root Application Module instances.

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

Call applyChangeSet to apply changes commited by another transaction. The integer id parameter (returned by commitAndSaveChangeSet) identifies the change set to be found in the persistent store.

After this call, this transaction's cache is synchronized with the changes from the change set.

For an example of how to use applyChangeSet, see commitAndSaveChangeSet.

Parameters:
id - an integer representing the change set to apply to the transaction.
See Also:
commitAndSaveChangeSet(), removeChangeSet(int)

removeChangeSet

public void removeChangeSet(int id)
Removes the change set that defines the changes to EntityImpls within a transaction.

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

For an example of how to use removeChangeSet, see commitAndSaveChangeSet.

Parameters:
id - an integer representing the change set to remove from the persistent store.
See Also:
commitAndSaveChangeSet(), applyChangeSet(int)

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:

 // Assume that appMod has been declared and initialized elsewhere.
   try {  if (updateAttr(vo, newAttrVal)) {
       // Commit changes to the database, making
       // updated data available to other Application Modules.
       appMod.getTransaction().commit();
       System.out.println("\n Transaction committed. \n");
     }
   else {
       appMod.getTransaction().rollback();
       System.out.println("\n Transaction rolled back. \n");
    }
 } catch (Exception e) {
       e.printStackTrace();
 }
 

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

See Also:
DBTransaction, TransactionListener.afterRollback(TransactionEvent), TransactionListener.beforeRollback(TransactionEvent)

clearEntityCache

public void clearEntityCache(java.lang.String entityName)
Clears the cache of the specified Entity Object. A value of null clears the caches of all Entities. If a View Object uses the Entity Object, the View Object's cache will be cleared as well.

Parameters:
entityName - the name of the entity whose cache is to be cleared. If null, caches for all entities are cleared.

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.

 public static void demoUpdateColumn(ApplicationModule appMod) {
     String sqlStr = "UPDATE EMP " +
                     "SET MGR=7007 " +
                     "WHERE MGR=7698 ";

     int n = appMod.getTransaction().executeCommand(sqlStr);
     System.out.println("Updated " + n + " rows.");
   }
 

Be careful when using executeCommand, because it will execute any valid SQL statement. For example, you could perform an operation like the following DDL command:

 appMod.getTransaction().executeCommand("DROP TABLE MYTEMPTABLE");
 

A pending database transaction could be committed inadvertently due to the implicit commit performed by DDL operations, as well as having any row locks released.

Parameters:
command - a valid SQL statement.
Returns:
the number of rows affected.
Throws:
InvalidParamException - if command is empty.
SQLStmtException - if command fails.

dumpQueryResult

public java.lang.String dumpQueryResult(java.lang.String query,
                                        java.lang.String dumpClassName,
                                        java.lang.String[] data)
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.

The following code example uses dumpQueryResult.

 public static void demoSimpleFetch(ApplicationModule appMod) {
       // Define and execute a simple SQL statement.
       String sqlStr = "SELECT Emp.ename FROM EMP Emp ";
       // dumpQueryResult is a utility method for testing queries.
       String result = appMod.getTransaction().dumpQueryResult(sqlStr,
                                    "oracle.jbo.server.QueryDumpTab",
                                      null);

 System.out.println(sqlStr);
 System.out.println(result);  }
 

Parameters:
query - the SQL query statement.
dumpClassName - the class that dumps the result to a string.
data - an array of data items.

createRef

public java.lang.Object createRef(java.lang.String structName,
                                  byte[] data)
Internal: Applications should not use this method.


getConnectionMetadata

public ConnectionMetadata getConnectionMetadata()
Returns a metdata structure that describes the transaction's JDBC connection.


setBundledExceptionMode

public void setBundledExceptionMode(boolean flag)
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.


isBundledExceptionMode

public boolean isBundledExceptionMode()

addTransactionStateListener

public void addTransactionStateListener(TransactionStateListener target)

removeTransactionStateListener

public void removeTransactionStateListener(TransactionStateListener target)

addViewClearCacheListener

public void addViewClearCacheListener(ViewClearCacheListener target)

removeViewClearCacheListener

public void removeViewClearCacheListener(ViewClearCacheListener target)

Oracle ADF Model and Business Components API Reference 10.1.2 B14022-01

 

Copyright © 1997, 2004, Oracle. All rights reserved.