Application Managed Entity Manager created outside the transaction do not automatically join the transaction. So case A and B will give exception. In C the entity manager joins the transaction using joinTransaction method and in D the entity manager is created in the transaction. So they are correct answers.
1). EntityManager.flush method must be called within an active transaction context. 2). It is the responsibility of the application to associate the entity manager with the transaction by calling EntityManager.joinTransaction.
Therefore calling flush, without associating the application-managed entity manger (that was created outside the scope of the active transaction) with the active JTA transaction, results in throwing TransactionRequiredException. According to spec, A and B are wrong.
However, I tried it in Glassfish and it was not required to explicitly call EntityManager.joinTransaction, I was able to sucessfully perform operations from A and B without calling EntityManager.joinTransaction. Glassfish uses Toplink which provides the JPA functionality for the EJB 3.0 Reference Implementation. It is probably another Glassfish's inconsistency with spec.
In this case exception will not be thrown. The persist, merge, remove, and refresh methods MUST be invoked within a transaction context when an entity manager with a transaction-scoped persistence context is used. We use application-managed persistence context which by default is EXTENDED, so participating in the active transaction is not needed. However, since entity manager does not participate in transaction and EntityManager.flush method is not invoked 'emp' object state will not be saved to the database.
hi krishna, here are the following lines from "EJB 3 Java Persistence API" book. ------- An application-managed entity manager participates in a JTA transaction in one of two ways. If the persistence context is created inside the transaction, then the persistence provider will automatically synchronize the persistence context with the transaction. If the persistence context was created earlier (outside of a transaction or in a transaction that has since ended), the persistence context may be manually synchronized with the transaction by calling joinTransaction() on the EntityManager interface. Once synchronized, the persistence context will automatically be flushed when the transaction commits. -------------- This will make the answer more clear.
I could able to successfully persist the manager object. I am not using joinTrasaction() method. And another finding is that, If use the following code after the catch block it is giving illegal state exception
You are using container-managed entity manager and container is associating entity manager with the transaction. As for IllegalStateException, you are not allowed to invoke close on container-managed entity manager.