Handling transactions using Enterprise Bean
This section describes transaction support in Enterprise JavaBeans (EJB) programming models built into Sun ONE Application Server 7.
Note If you are not familiar with EJB technology, please refer to the Java software tutorial:
http://java.sun.com/j2ee/docs.html
For more information on EJB transaction support, see ENTERPRISE JAVABEANS SPECification 2.0 Chapter 17 "Transaction Support". For an overview of the Sun One Application Server, see the "Sun ONE Application Server Enterprise JavaBeans Technical Introduction" and Sun ONE Application Server Product Description.
This section describes the following topics:
JTA and JTS transaction support use container management transactions with bean management transaction setting transaction timeout processing isolation level
JTA and JTS transaction support
J2EE includes support for distributed transactions through two specifications:
Java Transaction API (JTA) Java Transaction Service (JTS)
JTA is a high-level protocol API that is not implemented, the API enables applications and application servers to access transactions.
JTS specifies the implementation of the transaction manager, which supports JTA below the API and implements the OMG Object Transaction Service (OTS) 1.1 specification Java mapping. JTS uses the Internet ORB Agreement to Communicate Transactions (IIOP).
The current transaction manager implementation method supports JTS and JTA. The EJB container itself uses the Java transaction API interface to interact with JTS.
J2EE Transaction Manager Controls all EJB transactions (except Beans Manage Java Database Connections (JBDC) transactions) and enables Enterprise Beans to update multiple databases within a transaction.
About transaction processing
As a developer, you can write applications that update data in multiple databases, which are distributed between multiple sites. This site can use the EJB server provided by different vendors.
This section provides an overview of the following topics:
Flat Transaction Global and Local Transaction Demagration Model Submission Option Management and Monitoring
Flat transaction
Enterprise JavaBeans Specification 2.0 needs to support the plane (with nested relative) transactions. In a flat transaction, each transaction is separated from other transactions in the system and is independent of other transactions. You cannot start another transaction in the same thread before the current transaction ends.
Flat transactions are the most popular models and support for most commercial database systems. Although nested matters have more particle size of the transaction, the commercial database system that supports them is much less.
Global and local affairs
It is important to understand that the difference between global affairs and local affairs is very important when understanding the SUN ONE application server.
Global Transactions - Explorer Management and Coordination Transactions can span multiple databases and processes. Resource Manager Generally uses the XA Second Phase Submission protocol to interact with the Enterprise Information System (EIS) or database. Local Transaction - Local in a single EIS or database and limits transactions within a single process. Local transactions do not involve multiple sources of data.
Local and global transactions use the javax.transaction.usertransaction interface division boundary, and the client must use this interface. Local transactions do not use a transaction manager, resulting in faster processing.
At first, all matters are local. If the non-XA data source connection is the first resource connection registered in the transaction range, the non-XA data source connection is a global transaction when "another" XA data source connection adds this connection. If another non-XA data source connection is attempting to join, an exception is generated.
Sun One Application Server works in global or local transaction mode, but cannot mix two modes in the same transaction. Note If your app uses global transactions, you must configure and enable the corresponding Sun ONE Application Server Explorer. For more information, see the Sun ONE Application Server Management Interface Help and Administrator's Guide.
Dimensional model
Developers can choose to use the programming transaction in EJB code (bean management) or use the active boundary (container management). Regardless of the Enterprise Bean uses bean management or container management transactional, transaction management is implemented by the EJB container and Sun One Application Server. Vessels and Server Implementing the necessary low-level transaction protocols, such as the second-stage submission protocol between the transaction manager and the SUN ONE message queue provider, the transaction context propagation, the distributed two-stage submission, etc.
The following sections describe these boundary models:
Container management transaction Bean management transaction
Container management transaction
One of Enterprise Beans is to support container management transactions, also known as active transactions. In an Enterprise Bean with a container management transaction, the EJB container sets the boundary of the transaction.
Note You can use the container management transaction with any Enterprise Bean type (session, entity or message drive type), but entity beans can only use container management transactions.
The container management transaction is developed because the EJB code does not explicitly marks the boundary of the transaction. That is, the code does not include statements that start and end transactions. Container is responsible:
Differential transaction contextual boundaries, and transparently disseminate transaction contexts with transaction manager to ensure that all participants in the transaction can see the result
Bean management transaction
The EJB specification uses javax.transaction.usertransaction to support the BEAN management transactional boundary. For bean management transactions, you must perform Java Naming and Directory Interface (JNDI) lookups to get the useertransaction object.
Note You can use the bean management transaction for session or message drive type Beans, but entity beans must use container management transactions.
There are two types of bean management transactions:
JDBC Type - You can divide the boundaries of JDBC transactions using the submission and rollback method of the connection interface. JTA Type - You call the beginning, submission, and rollback method of the UserTransaction interface to divide the boundaries of JTA transactions.
Submit option
The EBJ protocol can provide the container to select the flexibility of selecting an instance status disposed mode when submitting a transaction. This allows the container to best manage the status of how to cache entity objects and how to associate entity object identities with EJB instances.
There are three submission options:
Option A - Container Cache Ready Instance between Transactions. The container ensures that the instance can exclude the status of the object in the persistent storage.
In this case, the container does not have to synchronize instances in the persistent storage at the beginning of the next transaction.
Note Sun ONE Application Server 7 does not support submission option A.
Option B - Containers Cache ready instance between transactions, but the container does not guarantee the status of the instance exclusive to access the object in persistent storage. This is the default value. .
In this case, the container must synchronize the instance by calling EjbLoad from the persistence store at the beginning of the next transaction.
Option C - Containers are not cache ready instances between transactions. In contrast, return the instance to the available instance pool after a transaction is completed.
The life cycle called for each business method to submit option C looks as follows:
EJBACTIVATE-> EJBACTIVATE-> EJBLOAD -> Business Method -> EJBStore -> Ejbpassivate If there are multiple transactional clients to access the same entity EJBOBJECT, the first client gets ready instance, and subsequent parallel clients get new from the pool Example.
Sun One Application Server Deployment Descriptor has an element commit-option, which specifies the submission option to use. Instantiate the appropriate handler according to the specified submission option.
Note Assume that the submission option A is used, the developer is responsible for ensuring that only this app is updating the database. In other words, this is not the responsibility of the container.
Management and monitoring
Administrators can control the following entire instance transaction service attributes in the Server.xml file:
Automatic-recovery timeout-in-seconds tx-log-directory heuristic-decision keypoint-interval log-level monitoring-enabled
For further instructions on these properties, see the Sun One Application Server Administrator Profile Reference.
In addition, administrators can use the statistics monitoring transactions in the Transaction Manager, and the statistics contain information about the following activities: the number of transactions that complete / roll / recover, the current processed transaction, and so on.
For information on managing and monitoring transactions, see the Sun One Application Server Management Interface Help and Sun ONE Application Server Administrator's Guide.
Use container management transactions
In general, the container starts a transaction immediately when starting an EJB method, and submits the transaction when the method exits. Each method can be associated with a single transaction.
Note that there is no nested transaction or multiple transactions within a method.
Container management transactions do not need to associate all methods with transaction. When deploying Enterprise Beans, you specify which methods of the bean are associated with transaction by setting transaction properties.
Although Bean with container management transaction requires less code, such beans have a limitations:
When a method is executed, the method can only be associated with a transaction or not with any transaction.
If this limitation makes it easy to encode beans, bean management transactions may be your best choice.
When submitted, the transaction prompts the container Bean to complete its useful work and inform the container to associate its status with the basic data source. The container allows the transaction to be completed, then release the bean. The result set associated with a submitted transaction is no longer effective. The container is then issued to the work that is associated with the basic data source for the request of the same bean.
Be careful not to explicitly submit a transaction that is started.
Any participant can roll back the transaction.
The following sections are related to the use of container management transactions related to ENTERPRISE BEAN:
Specifies that transaction attribute rollback container management transaction synchronization session bean instance variable container management transaction is not allowed
Specify transaction attribute
Transaction attributes are parameters for controlling transaction.
Since the transaction property is stored in the deployment descriptor, the transaction property can be changed in multiple phases deployed by the J2EE application: When creating EJB, when assembled (package), or during deployment. However, EJB developers should be responsible for specifying properties when creating EJBs. Properties should be modified only when assemblers assemble components into large applications.
Note Don't expect people who deploy J2EE applications to specify transaction properties.
You can specify transaction properties for the entire Enterprise Bean or for individual methods. If you have specified an attribute for a method, you specify another property for the bean, the property specified by the method is preferred.
Tip If you cannot determine how you set a transaction in the EJB deployment descriptor, specify the container management transaction. The Required transaction property is then set for the entire Enterprise Bean. In most cases, this method is effective. For more information on the EJB deployment descriptor file, see "Creating Deployment Descriptors."
This section describes the following topics:
Different attributes require attribute values
Different attribute requirements
When specifying properties for individual methods, requirements are required to vary with the type of beans.
Session bean - requires the properties defined for business methods, but does not allow them to create methods. Entity bean - requires business, creation, deleting, and looking for transaction properties for programs. Message drive type bean - Required or NotSupported required for the onMessage method.
Attribute value
A transaction attribute can have one of the following values:
Required Requiresnew Mandatory NotSupported Supports Never
Required
If the client is running within a transaction, the method of Enterprise Bean is called, the method is executed within the client's transaction. If the client is not associated with a transaction, the container starts a new transaction before running the method.
Prompt Required attribute valid for most transactions. Therefore, you may need to use it as a default value, at least in the early stages of development. Since the transaction attribute is active, you can easily change it later.
Requiresnew
If the client is running within a transaction, and the EJB method is called, the container takes the following steps:
Hang a client's transaction. Start a new transaction. Entrust the call to the method. Reply to the client after the method is completed.
If the client does not associate with a transaction, the container starts a new transaction before running the method.
To ensure that the method is always running within a new transaction, you should use the RequiresNew property.
Mandatory
This method is executed in the client's room if the client is running within a transaction, and the EJB method is called. If the client is not associated with a transaction, the container generates TransactionRequiredException.
If the EJB method must use the client's transaction, use the Mandatory property.
NotSupported
If the client is running within a transaction and calling the EJB method, the container hangs the client's transaction before calling the method. After the method is complete, the container restores the client's transaction.
If the client does not associate with a transaction, the container does not start a new transaction before running the method.
Supports
This method is executed within the client's transaction if the client runs within a transaction and calls EJB. If the client is not associated with a transaction, the container does not start a new transaction before running the method.
Note that due to method transaction behavior changes, you should be careful to use the Supports properties.
NEVER
If the client runs within a transaction and calls Enterprise Bean, the container generates RemoteException. If the client is not associated with a transaction, the container does not start a new transaction before running the method.
Use the NotSupported property for methods that do not require transactions. This property can improve performance due to additional overhead of transaction calls.
The following table summarizes the impact of the transaction attribute. The left list lists the transaction attribute, lists the types of client transactions, and lists the transaction types of the business method. The transaction can be T1, T2 or not. (T1 and T2 transactions are controlled by the container.)
T1 transaction - associated with a client that calls a method in the enteprise bean. In most cases, the client is another Enterprise Bean. T2 transaction - starts from the container before execution. NONE - In the third column, the word None refers to the business method is not executed within the transaction of the container control. However, the database calls in such a business method may be controlled by the transaction manager with a database. Transaction attribute and range transaction attribute client's transaction business method transaction REQUIRED NS T2 T1 RequiresNew None T2 T1 T2 Mandatory No error T1 NOTSUPPORTED None T1 None No T1 None No TI Error
Rollback container management transaction
There are two ways to return the container management transaction:
First, if a system is generated, the container automatically rolls back the transaction. Second, by calling the setrollbacknly method of the EJBContext interface, the bean method indicates the container rollback transaction. If the container produces an exception, rollback is not automated, but it can be started by calling SetrollbackOnly.
When the container rolls back a transaction, the container always revokes the SQL call for the transaction to make changes to the data. However, only in the entity bean, the container will revoke changes to the instance variable (the container performs this operation by automatically calling the EJBLOAD method of the entity bean, and the EJBLOAD method loads the instance variable from the database.)
Rollback happens, session beans must explicitly reset any instance variables that have been changed in the transaction. The easiest way to reset the instance variable of session beans is to implement the Sessionsynchronization interface.
Instance variable of synchronous session bean
The sessionsynchronization interface (optional in the session bean) allows you to synchronize the instance variable with the corresponding value in the database. Containers call sessionsynchronization methods at all major phases of transactions - Afterbegin, BeforeCompletion, and AfterCompletion.
Afterbegin Method - Notification Example The new transaction has begun. The container calls AFTERBEGIN directly before calling the business method. The Afterbegin method is a good place to load instance variables from the database. BeforeCompletion method - The container calls the BeforeCompletion method before the business is completed. The BeforeCompletion method is the last chance of the session bean (by calling the setrbackonly) rollback transaction.
If you do not update the database with the value of the instance variable, the session bean can do this in the BeforeCompletion method.
Aftercompletion method - identifying the transaction has been completed. This method has a Boolean parameter. If a transaction is submitted, the parameter is True.
If a rollback occurs, the session bean can refresh the real-induced variable from the database in the AfterCompletion method.
There is no method in container management transactions
For container management transactions, do not call any method that may interfere with the transaction boundaries set. The way to call the call is:
Java.sql.connection's commit, setuTocommit, and rollback method avax.ejb.ejbcontext's getUsertransaction method javax.transaction.usertransaction's method
However, you can use these methods to set the boundaries in the bean management transaction. Use Bean Management Transactions
In a bean management transaction, the code in the session bean or message drive type bean clearly marks the boundaries of the transaction. By moving transaction management to the bean level, you can put all the BEAN's activities - even those that are not directly connected to database access - the same transaction control with your database. This ensures that all application parts of a BEAN control are run as part of the same transaction.
In the fault situation, either submit everything that Bean is either rolling everything.
The following sections are related to the development of Enterprise Bean with bean management transactions:
Select the transaction type to return to the method in the bean management transaction without commit
Select transaction type
When encoding a bean management transaction for a session bean or message drive type bean, you must be sure to use JDBC or JTA transaction.
Note that in a session bean with a bean management transaction, JDBC and JTA transactions can be mixed together. However, this is not advocated because this makes it difficult to debug and maintain code.
The following sections discuss two types of transactions:
JDBC transaction JTA transaction
JDBC transaction
JDBC transactions are controlled by the transaction manager of the database. When the original code is included in the session bean, you may need to use JDBC transactions.
To encode a JDBC transaction, you call the submission and rollback method of the java.sql.connection interface. The start of the transaction is not clear. The transaction starts with the first SQL statement that follows the recent commit, rollback or connection statement. (This rule is usually accurate, but may vary with the database vendor.)
For additional information about JDBC, see "J2EE Features and Services" in the Sun ON App Server Developer's Guide.
JTA transaction
JTA allows you to divide your transactions without being implemented by the transaction manager. J2EE SDK uses JTS to implement a transaction manager. But your code does not call the JTS method directly, but call the JTA method, the JTA method then calls the lower JTS routine.
JTA transactions are controlled by J2EE transaction manager. You may need to use a JTA transaction because JTA transactions can distribute updates to multiple databases from different vendors. The transaction manager of a database may not work with the heterogeneous database.
J2EE Transaction Manager does have a limitations - no standing transactions are supported. In other words, J2EE can start a transaction for an instance after the end of the previous transaction.
For additional information about JTA, see "J2EE Features and Services" in the Sun Open Application Server Developer Guide.
Returns without submitting
Starting a BEAN management transaction in a business method, a BEAN management transaction must be submitted or rollback transactions before you can return. However, there is no such restriction. In a stateful session bean containing the JTA transaction, multiple client calls remain related to the relationship between the BEAN instance and the transaction.
Methods not allowed in Bean management transactions
For bean management transactions, do not call the getRollbackOnly and SetrollbackOnly methods for the EJBContext interface. Use these methods only in the container management transaction.
Note For Bean Management Transactions, call the getStatus and Rollback methods for the Usertransaction interface.
Setting transaction timeout
For container management transactions, you can control the transaction time interval by determining the value of the timeout-in-seconds attribute in the server.xml file. For example, you will set the timeout value to 5 seconds as follows:
Timeout-in-seconds = 5
With this setting, if the transaction is not completed within 5 seconds, the EJB container rolls back the transaction. Note that Enterprise Bean that is only used with container management transactions will be affected by the timeout-in-seconds attribute. For Enterprise Beans that manages JTA transactions using beans, you call the SettransActionTimeout method for the Usertransaction interface.
Treatment isolation level
Transactions not only ensure that the statements contained in the transaction completely (or roll back), but also the data modified by the statement. Isolation level describes the visible data of the updated data for other transactions.
If the transaction allows other programs to read unauthorized techniques, it may increase performance because other programs do not have to wait for the end. However, this may also result in problems - if the transaction rolls back, another program may read the error data.
For entity beans with beans management persistence, and for all session beans, you can programmatically set the isolation level by the API provided by the basic database. For example, a database allows you to allow unauthorized reads by calling the SetTransactioniSolaion method.
For entity beans that use container management persistence, you can set the isolation level using the consistency element in the Sun-cmp-mapping.xml file.
Note Don't change the isolation level in your transaction. Normally, such changes will make database software unclear commitments. Since the isolation level provided by the database vendor may change, you should check the database documentation for more information. The isolation level is standardized for the J2EE platform.
Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
Last Updated October 09, 2002