EJB self-managed transactions

Source: Internet
Author: User

 

If you declareIf the transaction control of bean is TX_BEAN_MANAGED, the bean can access the transaction service. When transaction control is applied to a single method, this control can only be applied to the whole bean. bean's ability to access the transaction service cannot only work for a method. Therefore, one method declares that the transaction control is TX_BEAN_MANAGED, And the other method declares that other different transaction control is incorrect. The vendor's Installation tool should be able to detect and report this error. Bean accesses the transaction service by using the SessionContext or EntityContext parameters of the setSessionContext () or setEntityContext () method during initialization. These interfaces are subclasses of EJBContext.

EJBContext is defined as follows:

Public interface javax. ejb. EJBContext {
Public Identity getCallerIdentity ();
Public boolean isCallerInRole (Identity other );
Public EJBHome getEJBHome ();
Public Properties getEnvironment ();
Public UserTransaction getUserTransaction () throwsIllegalStateException;
Public boolean getRollbackOnly ();
Public void set RollbackOnly ();
}

Once the bean obtains a reference of UserTransaction, it can be used to manage its own transactions. The stateful Session bean method creates a transaction and returns the result without terminating the transaction. If there is a thread that calls the bean method, the container checks whether there are any active transactions created by bean. If the called transaction is the same transaction, the container will allow the thread to re-enter the bean. if the bean is in a transaction and the thread that executes different transaction contexts tries to enter the bean, the container will block this thread until the bean transaction ends. If the bean is not in the transaction when the thread tries to enter the transaction, the thread will execute a transaction of its own, and the container will suspend the current transaction of the thread to allow the thread to enter. Once the thread leaves the method, the previous transactions of the thread will be restored, and the container will not terminate any transactions created by the method.

For stateless session beans and entity beans, the bean method cannot be returned when the transaction is active. The container throws an exception.

Leaving a tranaction active authentication SS method CILS is stateful, and is not allowed for stateless session beans. fro similar reasons, entity beans are also not allowed to maintain an open transaction state loss SS method callwhen the bean has declared the TX_BEAN_MANAGED transaction control.

Session synchronization Interface
Stateful and stateless session beans can both access the database and participate in a transaction. To allow the bean to execute its tasks in a transaction, the bean developer can implement the javax. ejb. SessionSynchronization interface in the bean. The container can automatically detect this interface, and the container will use the method in this interface to get the transaction status information of the bean. The Entity bean does not support this interface. Because the Entity bean is implicitly transaction aware, the container uses different methods to control the Entity bean in a transaction.

SessionSynchronization interface is defined as follows:

Public interface javax. ejb. SessionSynchronization {
Public void afterBegin () throws RemoteException;
Public void beforeCompletion () throws RemoteException;
Public void afterCompletion (boolean yn) throws RemoteException;
}

In fact, a transaction does not belong to a special bean instance. A thread executed by a client or container creates a transaction and executes the transaction when executing the code in the bean. If a thread with a transaction context is about to enter a session bean, the container first calls its afterBegin () method. Bean can record all commercial methods running in transactions and then perform transaction operations. If the internal flag of an operation shows that the thread is running outside the transaction, the request for executing the transaction operation is rejected. Until the afterCompletion () method is called, bean will continue to think that all calls to commercial methods are executed in the transaction. Bean will push the internal flag out, indicating that subsequent transaction requests will be rejected.

If a thread in the transaction context tries to enter a Bean that is already part of another transaction ,. the Container blocks the entry until the previous transaction is committed or rolled back, And the afterCompletion () method is called. In this case, the Bean is allowed to restore its status. The Container is responsible for providing these actions. When the Container finds that it is about to commit a transaction, it will call the beforeCompletion () method on all session beans of the transaction. This gives Bean enough opportunity to end transaction operations, such as writing data to the database before submission. If the Container finds that a transaction is to be rolled back, the BeforeCompletion () method will not be called, it is meaningless to write the data generated by a rollback transaction to the database.

AfterCompletion () is called when a transaction is about to be committed or rolled back to notify the final result of the Bean transaction operation. Bean can use this information to modify its internal state, but it cannot use this information to maintain any transactions it will save. Although session beans can be created, committed, and rolled back to their own transactions, it is generally not recommended to do so.

The SessionSynchronization interface does not provide the ability to integrate external and internal transactions. If a session bean implements this interface, it means that it must maintain the transaction state between method calls. Specifically, this implies that the bean is in a transaction between afterBegin () and afterCompletion () calls. In this way, if a bean implements the SessionSynchronization interface and declares in the Assembly operator that it is stateless, it is an error. The Installation tool provided by the vendor should be able to capture and report this error. Stateless session beans can join a transaction, but they cannot implement this interface. The transaction can be TX_BEAN_MANAGED, or the container can start and submit the transaction at the method entry and from the return of the method. Container cannot allow a thread in an existing transaction to enter the method, because the stateless Bean method cannot know whether the running thread is in a transaction.

One way to solve this problem is to make the container suspend existing transactions, and the forced method always considers that the thread is not running in a transactional context. Stateful Bran can intervene in transactions without implementing this interface. However, the assembler must be carefully configured so that the business method can always run in the correct transaction state. Bean itself does not have the right to obtain its own transaction status through this interface.

Join transaction
The EJBContext interface is described in the previous section. There are two methods:

Public boolean getRollbackOnly ();
Public void setRoolbackOnly ();

These methods can be used by any bean, not just those beans that declare their transaction control as bean-managed. In fact, beans that process their own transactions will not use these methods, because they are not used to communicate the transaction state with the external Transaction Manager.

When a bean calls the setRollBackOnly () method, it is asking the Transaction Manager when to end the current transaction to be rolled back. It will give a vote to the result of the transaction it participates in. These methods still exist in the UserTransaction interface, but since most beans do not access this interface, these methods must be provided directly to the bean in EJBContext. Note that this method does not trigger a rollback operation. It simply sets a flag, indicating that the transaction should be rolled back at the end. Unlike the JavaBan attribute setting method, this method does not use a boolean value as a parameter. This method is specially designed so that one bean cannot change the rollback request of another bean. A bean may want to use the getRoolBackOnly () method to check the status of the current transaction. If another bean has marked this transaction as rollback, then the bean being called can be inferred and determined not to execute the operations that are mandatory, such as database update, these operations may be reversed at the end of the transaction.

Customer transaction
Despite being required by a JEB vendor, a large server provider may decide to provide a class so that users can directly access the Transaction Manager. When you need to call beans on two different servers in the same context, you may want to do so. Of course, the operator of each bean can allow such behavior. You can create a transaction and call the Business Method on two different beans on two different servers. The transaction context is also passed as part of the call. Once the call ends, the user ends the transaction with speculation. Stub and skeleton generated by the container vendor will support implicit transfer of transaction context.

Here is a possible example:

Current current = new Current ();
Current. setServiceProvider (txMgrURL );
Current. create ();
Current. begin ();
Current. doSomeWork ();
RemRef1.doSomeWork ();
RemRef2.doMoreWork ();
Current. commit ();

Transaction Management for database operations
Bean certainly wants to use JDBC to establish a connection to the database and operate on it. However, to comply with the container transaction management mode such as EJB, the connection cannot use the automatic commit feature and should not attempt to commit or roll back the connection.

The role of the Container determines whether to commit or roll back all the actions performed in this transaction. This is a good question: how does the container view and manage the database connections created inside the bean method. Although it is not explicitly mentioned in the Specification, ejbs can only use JDBC drivers, and JDBC is also used in combination with ejbs. When a database connection is created, the driver transparently registers the connection to the current transaction of the thread being executed. When the container decides to end the transaction, the database connection will automatically end it. In OTS terminology, database connections are unrecoverable resources, and transaction services are implicitly managed with the help of container. Although non-transaction-aware JDBC Driver can be used in this case, the developer must be aware that any operation performed on the database connection is not a bean transaction, the developer must also ensure that the database connection transaction ends before returning from the method. It is unreliable to try to use the SessionSynchronization interface to merge database connection transactions and bean transactions.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.