Application vs Container Managed EntityManager

Hayati Guvence picture Hayati Guvence · Dec 8, 2011 · Viewed 10.2k times · Source

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?

Answer

mprabhat picture mprabhat · Dec 8, 2011

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.