tags:

views:

82

answers:

3

Does executing EntityManagerFactory.createEntityManager() reutrn new instance each time? or it returns the cached copy of the same EntityManager each time?

A: 

EntityManagerFactory returns new instance of EntityManager on each call to EntityManagerFactory.createEntityManager().

If you execute...

emf = Persistence.createEntityManagerFactory("basicPU");
 for (int i = 0 ; i<10; i++){
     System.out.println(em = emf.createEntityManager());
 }

It Prints:

org.apache.openjpa.persistence.EntityManagerImpl@18105e8
org.apache.openjpa.persistence.EntityManagerImpl@9bad5a
org.apache.openjpa.persistence.EntityManagerImpl@91f005
org.apache.openjpa.persistence.EntityManagerImpl@1250ff2
org.apache.openjpa.persistence.EntityManagerImpl@3a0ab1
org.apache.openjpa.persistence.EntityManagerImpl@940f82
org.apache.openjpa.persistence.EntityManagerImpl@864e43
org.apache.openjpa.persistence.EntityManagerImpl@17c2891
org.apache.openjpa.persistence.EntityManagerImpl@4b82d2
org.apache.openjpa.persistence.EntityManagerImpl@179d854
Digambar Daund
That doesn't prove anything, that just shows that your particular JPA implementation and environment and test returns a new instance each time.
skaffman
I think it proves that executing EntityManagerFactory.createEntityManager() returns new instance of EntityManager on each call, does not returns some cached EntityManager Object.
Digambar Daund
No, it proves it *just for your test*, it proves nothing about what other implementations or environments would do.
skaffman
+1  A: 

The Javadoc is unambiguous:

Create a new application-managed EntityManager. This method returns a new EntityManager instance each time it is invoked.

skaffman
if so then why executing below lines throw EntityExistsExecptionemf = Persistence.createEntityManagerFactory("basicPU"); Item item = new Item(); for (int i = 0 ; i<10; i++){ em = emf.createEntityManager(); em.persist(item) } But executing below lines adds new record to database... Item item = new Item(); for (int i = 0 ; i<10; i++){ emf = Persistence.createEntityManagerFactory("basicPU"); em = emf.createEntityManager(); em.persist(item) }
Digambar Daund
@Digambar: I have no idea. That's a different question entirely.
skaffman
@skaffman: thanks!!
Digambar Daund
+1 there is indeed no ambiguity
Pascal Thivent
A: 

To second skaffman's answer, here is an extract of the JPA 1.0 specification:

5.9.2 Provider Responsibilities

The Provider has no knowledge of the distinction between transaction-scoped and extended persistence contexts. It provides entity managers to the container when requested and registers for synchronization notifications for the transaction.

  • When EntityManagerFactory.createEntityManager is invoked, the provider must create and return a new entity manager. If a JTA transaction is active, the provider must register for synchronization notifications against the JTA transaction.
Pascal Thivent