Posted by Unknown on 11:53 PM
Labels:

With Container Managed Transactions (CMT) in an EJB3 container, transaction demarcation is done in session bean annotations or deployment descriptors, not programmatically. The EntityManager will automatically be flushed on transaction completion (and if you have injected or lookup the EntityManager, it will be also closed automatically).If an exception occurs during the EntityManager use, transaction rollback occurs automatically if you don't catch the exception. Since EntityManager exceptions are RuntimeExceptions they will rollback the transaction as per the EJB specification.
If you work in a CMT environment, you might also want to use the same entity manager in different parts of your code. Typically, in a non-managed environment you would use a ThreadLocal variable to hold the entity manager, but a single EJB request might execute in different threads (e.g. session bean calling another session bean). The EJB3 container takes care of the persistence context propagation for you. Either using injection or lookup, the EJB3 container will return an entity manager with the same persistence context bound to the JTA context if any, or create a new one and bind it. In other words, all you have to do in a managed environment is to inject the EntityManager, do your data access work, and leave the rest to the container. Transaction boundaries are set declaratively in the annotations or deployment descriptors of your session beans.
The life cycle of the entity manager and persistence context is completely managed by the container. The persistence context lifetime has transaction scope, so the persistence context ends when the transaction is committed or rolls back. Transaction management uses container-managed transactions with the required transaction attribute. This means that any business method will get invoked by the container in the context of a transaction (either an existing or a new one).our persistence context ends when the method returns because that is when the transaction ends. At this stage, the connection between all managed entities and the entity manager is removed and the entities change to the detached state. In the detached state, entity state is not synchronized with the database.
So, how do we change the account so that the database is actually updated? We need to do two things: get a new persistence context, and transfer the entity to the managed state again.

//CMT idiom through injection @PersistenceContext(name="PU Name")
EntityManager em;

0 comments: