【问题标题】:Is there a "clean" solution for the "Object Manager has been closed" error (JPA)?“对象管理器已关闭”错误(JPA)是否有“干净”的解决方案?
【发布时间】:2012-01-19 08:25:40
【问题描述】:

我在 Google App Engine 上使用 JPA(不是 JDO),这是我的服务方法的典型示例:

@Autowired
EntityManagerFactory entityManagerFactory;

public Collection<Message> getAll() {
    EntityManager em = entityManagerFactory.createEntityManager();
    Collection<Message> result = null;

    try {
        Query query = em.createQuery("SELECT e FROM Message e");
        result =  query.getResultList();
        //The workaround
        //if(result != null) result.size();
    } finally {
        em.close();
    }

    return result;
}   

当我尝试在方法之外使用集合时,我收到“著名”错误报告,即对象管理器已关闭。调用 size() 方法是一种解决方法,但我不喜欢这种“肮脏”的解决方案。我想知道没有任何方法可以使此集合分离或禁用延迟加载。

【问题讨论】:

    标签: java google-app-engine jpa google-cloud-datastore


    【解决方案1】:

    我不知道它是否“干净”,但经常推荐的方法是使用 servlet 过滤器,在您的代码运行之前创建一个线程本地 EntityManager,并在最后关闭它。

    【讨论】:

    • 这似乎是一个很好的解决方案。因为我使用 Springframework 而不是 thread-local,所以它应该是一个 request-scope bean。
    【解决方案2】:

    如果您使用的是 spring(如您所见),OpenEntityManagerInViewFilter 是将 EntityManager 暴露给视图的“正确”方式,从而允许在您的视图中延迟获取持久性集合。

    【讨论】:

      【解决方案3】:

      使用 GAE JPA 插件 v2;再简单不过了

      【讨论】:

        【解决方案4】:

        使用 Guice JPA 插件,再简单不过了。

        http://code.google.com/p/google-guice/wiki/JPA

        【讨论】:

          猜你喜欢
          • 2011-08-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-07-01
          • 2019-12-16
          • 2010-10-21
          • 2016-11-26
          相关资源
          最近更新 更多