My Quotes


When U were born , you cried and the world rejoiced
Live U'r life in such a way that when you go
THE WORLD SHOULD CRY






Thursday, June 5, 2014

@PersistenceUnit versus @PersistenceContext

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

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


PersistenceUnit injects an EntityManagerFactory
  • With EntityManagerFactory and @PersistenceUnit you should create/destroy EntityManager every time by hands and manage transactions too
    and PersistenceContext injects an EntityManager.
  • EntityManager interface is used and instantiated directly. It has an internal mutable thread-local reference to a real EntityManager
  • Implementations of methods just redirect calls to this real EntityManager.
  • And there is a servlet listener, that before each request obtain EM by calling EMF.createEntityManager()
  • and assign it to that inner reference of special EM.
  • Also this listener manages transactions by calling getTransaction().begin(), .commit() and .rollback() on the real EM

    for(int i=0; i < 100; i++){
       insert into table
    }
    
    Question is whether the above will use single connection (or) more connections.
  • The answer is below
  • A JPA EntityManager that is JTA managed will use the same JDBC/database connection for the duration of a JTA transaction.
  • So as long as your method is in a JTA transaction, your code will have the same connection.
  • Outside of a transaction, the container may acquire a new EntityManager for each operation,
  • Across every JTA transaction boundary the proxy will release its JPA EntityManager and acquire a new one (or at least clear it).
  • No comments :