Does executing EntityManagerFactory.createEntityManager() reutrn new instance each time? or it returns the cached copy of the same EntityManager each time?
views:
82answers:
3
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
2010-06-10 06:09:58
That doesn't prove anything, that just shows that your particular JPA implementation and environment and test returns a new instance each time.
skaffman
2010-06-10 07:19:13
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
2010-06-10 07:28:46
No, it proves it *just for your test*, it proves nothing about what other implementations or environments would do.
skaffman
2010-06-10 07:34:37
+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
2010-06-10 07:18:20
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
2010-06-10 07:26:31
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
2010-06-10 14:07:26