user237673
user237673

Reputation:

Does executing EntityManagerFactory.createEntityManager() reutrn new instance each time?

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

Upvotes: 0

Views: 1779

Answers (3)

Pascal Thivent
Pascal Thivent

Reputation: 570545

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.

Upvotes: 0

skaffman
skaffman

Reputation: 403591

The Javadoc is unambiguous:

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

Upvotes: 2

user237673
user237673

Reputation:

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

Upvotes: 0

Related Questions