PersistenceUnit vs PersistenceContext

user2377971 picture user2377971 · Jan 10, 2014 · Viewed 29k times · Source

In few project I have been successfully using

@PersistenceUnit(unitName = "MiddlewareJPA")
EntityManagerFactory emf;
...
EntityManager entityManager = emf.createEntityManager();

to obtain EntityManager for Database connection, but some days ago I was trying to move my project to Jboss EAP 6.2 and it couldn't create EntityManager. I was googling it and I found that I should try change @PersistenceUnit to

@PersistenceContext(unitName = "MiddlewareJPA")
private EntityManager entityManager;

to obtain EntityManager. It worked but I don't know why. What is the difference bettween PersistenceUnit and PersistenceContext? What are pros and cons of each one? Where should we be using one of them?

Answer

PersistenceUnit injects an EntityManagerFactory, and PersistenceContext injects an EntityManager. It's generally better to use PersistenceContext unless you really need to manage the EntityManager lifecycle manually.