Search code examples
javajpaentitymanager

Best way to close an entityManager


I have the following code:

    public Category findCategoryById(Long id) {
      EntityManager em = emf.createEntityManager();
      try {
          em.getTransaction().begin();
          Category category = categoryDAO.findCategoryById(em, id);
          em.getTransaction().commit();
          return category;
      } catch (Exception e) {
          throw e;
      } finally {
          em.close();
    }
  }

I'm handling the exceptions in my controller, but I want to make sure that entity manager is closed. I don't like that I am catching and re-throwing the error. I'm hoping to find better suggestions.

thanks


Solution

  • The best way is to not have to care about it. If your Entity Manager is container managed (for example if you are using ejb or spring and you haven't forced a specific bean/application managed behaviour) you should let the container handle the opening/close of the transaction and in general to worry about your persistence context. It's easier, safer and, with the exclusion of very specific cases, better. The manual close of the Entity Manager should be directly handled by you only in case of application managed context, to avoid connection pool exhaustion or other problems.