3

When should I close connection with database ? I create connection one time when application starting, and then I use entity manager in this way:

public void createItem(TYPE item){
        em.getTransaction().begin();
        em.persist(item);
        em.getTransaction().commit();
    }

public class Connection {  //creating connection (one time)
      private static final String PERSISTENCE_UNIT_NAME = "ejb";
      private static EntityManagerFactory factory;
      private static EntityManager em;

      static{
          factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
          em = factory.createEntityManager();
      }
      public static EntityManager getEntityManager() {
        return em;
      }
}

I think it does not make sense to close connection evey each operation (like create) and create new connecion when I want to save item again.

lucas999
  • 169
  • 1
  • 2
  • 11
  • 1
    Possible duplicate of [Hibernate EntityManager, is it supposed to be used as a singleton?](http://stackoverflow.com/questions/9370819/hibernate-entitymanager-is-it-supposed-to-be-used-as-a-singleton) – Raffaele May 02 '16 at 11:29

2 Answers2

4

You should not make entitymanager static, it should be an object that is removed after you do your transactions. This also mean that you should close it after your operation is finished. EntitymanagerFactory can stay static, you only need 1 for each program run. The reason as to why you should close it is that you are wasting resources on your device.

Longer/ better explanation on EMF https://stackoverflow.com/a/4544053/6270761

Community
  • 1
  • 1
namlik
  • 182
  • 1
  • 12
1

As far as i know the EntityManager is just abstraction to handle work-unit in ongoing transaction, if you created it using EntityManagerFactory which it is in current implementation you have to close it no matter what framework or template you are using.

If you obtained it using dependency injection (eg using EJB and @PersistenceContext annotation) you should not close it by hand i.e. it will close by embed dependency which you injected, the idea is to always close java.sql.Connection to prevent resource leak.

More over the application has finished using the entity manager factory, and/or at application shutdown, the application should close the entity manager factory. Once an EntityManagerFactory has been closed, all its entity managers are considered to be in the closed state as well.

Lunatic
  • 1,519
  • 8
  • 24