0

I am using JPA 2.1. Entity Managers are application managed here.

Sample Class:

public class TestDao {

private static EntityManagerFactory emf;

private static EntityManager em;

public static EntityManager initialize() {
    if (emf == null) {
        emf = Persistence.createEntityManagerFactory("persistence_unit");
    }
    return emf.createEntityManager();
}

public static void insert(Object obj){
    em.persist(obj);
}

When user first time uses TestDao.initialize(), it generates emf and em instances.

What will happen with this emf instance?

Does it always keep connection with the database?

Which is better way if I have both significant reads and writes:

  • create emf once (as I used above)
  • create new emf and em every time I interact with the database.
Dev
  • 11,996
  • 15
  • 57
  • 138
  • 1
    EMF can be re-used. Using that we can create multiple EMs. EM is the one who opens connection to the database. EMF is used to obtain an application managed EM. It is usually closed with the application close. – Sunil Dabburi May 20 '16 at 08:29

1 Answers1

0

As per the Factory Pattern, it should be created/initialized only once. So EntityManagerFactory should be only one through out the application. You can create EntityManager from this factory as and when required.

References: Factory Pattern, When should be factory instance be created?

Community
  • 1
  • 1
darshgohel
  • 352
  • 2
  • 12