Can anybody explain what is difference between :
@Resource UserTransaction objUserTransaction;
and
EntityManager.getTransaction();
And also what is container managed transaction? and how should I do it in my session facade if I want to insert three rows in table in transaction.
A UserTransaction is the interface used by client applications to manage transactions. Typically, a transactional application server will publish a UserTransaction through JNDI, and clients will get a reference to the UserTransaction using a lookup on the JNDI Context .
The UserTransaction interface defines the methods that allow an application to explicitly manage transaction boundaries. Method Summary. void. begin() Create a new transaction and associate it with the current thread.
EJB are transactional components. The transaction can be managed either by the applicaiton server itself (CMT - container-managed transaction), or manually by yourself within the EJB (BMT - bean-managed transaction).
EJB supports distributed transaction through the JTA specification. The distributed transaction is controlled using UserTransaction
, which has methods begin
, commit
, rollback
.
With CMT, the application server starts, commit and rollback the transaction (according to the transaction annotations) for you and you are not allowed to interfere. This means you must not access the UserTransaction
in this case. However, with BMT, you do that manually and you control the transaction yourself using the UserTransaction
.
Let's move now to the EntityManager
. A JPA implementation can be used either within an application server or stand-alone. If use in stand-alone, you need to use EntityManage.getTransaction
to demarcate the JDBC transaction yourself. If used within an application server, the EntityManager
cooperated with the JTA distributed transaction manager transparently for you.
Most of the time, you use CMT with @Required
annotation on the EJB. This means that you don't need to access neither UserTransaction
nor EntityManager.getTransaction
. The app. server starts and commits the transaction, but also takes care to rollback if an exception is raised. This is what I would recommend for your facade.
(There are more subtleties, such as the PersistenceContextType
or the manual enlistment of the entity manager in distributed transaction with EntityManager.joinTransaction
, but that's only if you use the technologies in a different ways as the default).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With