【问题标题】:How do I access EntityManager from within Grails service (JPA + GAE)如何从 Grails 服务 (JPA + GAE) 中访问 EntityManager
【发布时间】:2011-05-10 15:20:49
【问题描述】:

我在从 grails 服务中访问 EntityManager 时遇到问题:

我的设置如下...

  • 带有 AppEngine 和 GORM-JPA 插件的基本 Grails 应用程序
  • 几乎所有内容的默认设置。没碰过resources.groovy、persistence.xml等。

有些东西很好……

  • 我可以通过简单地添加“def entityManager”从控制器中访问 EntityManager。

但是...

  • 我有一个服务,我试图从中访问 EntityManager,但是,我得到一个“java.lang.IllegalStateException:EntityManager 已经关闭!”例外。
  • 插件是否在某处关闭了 EntityManager?我是否需要以某种方式更改 EntityManager 的范围?是否需要更新一些 XML 文件以确保正确注入?

    class GoogleCalendarService implements InitializingBean {
        void afterPropertiesSet() {
        }
    
    
    
       def entityManager
    
    
       public OAuthToken getAccessToken(User u) {
           //can't access entityManager from here
           entityManager.newQuery(...) //throws an IllegalStateException
       }
    
    }

一个奇怪的注释: 出于某种原因,如果我在 Jetty 启动并运行时重新保存服务,则该服务只能访问 EntityManager 一次。如果我单击重新加载(并让控制器再次访问该服务)该服务将无法再访问 EntityManager...

【问题讨论】:

    标签: google-app-engine grails jpa grails-plugin


    【解决方案1】:

    我想正确的方法是使用 EntityManagerFactory,如下所示:

    import org.springframework.orm.jpa.EntityManagerFactoryUtils
    
    class GoogleCalendarService implements InitializingBean {
        void afterPropertiesSet() {
    
        }
    
        def entityManagerFactory
        EntityManager em
    
        public OAuthToken getAccessToken(User u) {
            em = EntityManagerFactoryUtils.getTransactionalEntityManager(entityManagerFactory)
            //do stuff with em
        }
    }
    

    【讨论】:

    • 我试过了,但 entityManagerFactory 为空。有任何想法吗?谢谢
    猜你喜欢
    • 1970-01-01
    • 2015-01-16
    • 1970-01-01
    • 2014-07-07
    • 2012-01-30
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多