PersistenceUnit vs PersistenceContext

In few project I have been successfully using

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

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

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

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


答案 1

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


答案 2

I don't know how it works exactly in the Java EE, but in Spring, when you specify annotation, it injects . Where does it get ? It is wrong to create one for the whole application lifetime by calling . So instead a special implementation of interface is used and instantiated directly. It has an internal mutable thread-local reference to a real . Implementations of methods just redirect calls to this real . And there is a servlet listener, that before each request obtain by calling and assign it to that inner reference of special . Also this listener manages transactions by calling , and on the real . It is very simplified description of performed work. And I believe, that JEE container does the same thing, as Spring does.@PersistenceContextEntityManagerEntityManagerEntityManagerEntityManagerFactory.createEntityManager()EntityManagerEntityManagerEntityManagerEMEMF.createEntityManager()EMgetTransaction().begin().commit().rollback()EM

In general case it is better to inject , because with and you should create/destroy every time by hands and manage transactions too.EntityManagerEntityManagerFactory@PersistenceUnitEntityManager


推荐