简体   繁体   English

关闭entityManager的最佳方法

[英]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 谢谢

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. 如果您的Entity Manager容器管理的 (例如,如果您正在使用ejbspring并且您没有强制执行特定的Bean /应用程序管理的行为),则应让容器处理事务的打开/关闭,并且通常要担心您的持久性环境。 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. 仅在应用程序托管上下文的情况下,您才应直接处理Entity Manager的手动关闭操作,以避免连接池耗尽或其他问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM