2

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
  • 129
  • 1
  • 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

1 Answers1

2

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
  • 162
  • 12