Application vs Container Managed EntityManager

橙三吉。 提交于 2019-12-04 16:53:32

问题


I am currently having a problem with understanding a concept of JPA.

I am currently using/developing recent EclipseLink, Glassfish, Derby database to demonstrate a project.

Before I develop something in much bigger picture, I need to be absolutely sure of how this PersistingUnit work in terms of different scopes.

I have bunch of servlets 3.0 and currently saving user's associated entity classes in the request.session object (everything in the same war file). I am currently using Application-managed EntityManager using EntityManagerFactory and UserTransaction injection. It works smooth when it is tested by myself. The different versions of entities occur when 2 people accessing the same entities at the same time. I want to work with managed beans cross the same WAR, same persistence unit if possible.

I have read http://docs.oracle.com/javaee/6/tutorial/doc/bnbqw.html and bunch of explanations of those scopes which don't make sense at all for me.

Long story short, what are the usage and difference of app and container managed EntityManagers?


回答1:


When you say application managed transaction it means its your code which is supposed to handle the transaction. In a nutshell it means:

You call:

entityManager.getTransaction().begin(); //to start a transaction

then if success you will ensure to call

entityManager.getTranasaction().commit(); //to commit changes to database

or in case of failure you will make sure to call:

entityManager.getTransaction().rollBack();

Now imagine you have a container, which knows when to call begin(), commit() or rollback(), thats container managed transaction. Someone taking care of transaction on your behalf.

You just need to specify that.




回答2:


Container managed transaction(CMT) could be regarded as a kind of declarative transaction, in which case, transaction management is delegated to container (normally EJB container), and much development work could be simplified.

If we are in a Java EE environment with an EJB container, we could use CMT directly.

If we are in a Java SE environment, or a Java EE environment without an EJB container, we could still take advantage of CMT, one way is to use Spring, which uses AOP to implement declarative transaction management; Another way is to use Guice, which uses a PersistFilter to implement declarative transaction.

In CMT, a container (whatever an EJB container, Spring or Guice) will take care of the transaction propagation and commit/rollback stuff;

Application managed transaction (AMT) differs from CMT in that we need to handle transactions programmatically in our code.



来源:https://stackoverflow.com/questions/8432046/application-vs-container-managed-entitymanager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!