Grails hibernate会话打开/关闭和延迟初始化

时间:2018-05-03 16:58:38

标签: hibernate grails gorm lazy-loading grails-2.0

我有很多与会话有关的例外情况:

org.hibernate.LazyInitializationException failed to lazily initialize a collection of role: <...>, no session or session was closed
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session
org.hibernate.TransientObjectException: cannot lock an unsaved transient instance: <...>
org.hibernate.UnresolvableObjectException: No row with the given identifier exists

我想了解原因。 所以我已经激活了SQL日志,当我查看hibernate统计信息时,我可以看到80个会话已打开,80个已关闭,即使http请求未结束... 我认为OSIV(默认情况下在grails中激活)可能会阻止一些lazy-init异常,但是从我看到的,会话打开然后按需关闭(对于事务)。

那么为什么我不会在http请求结束前至少有一个会话保持打开状态?

您是否有任何理解/调查正在发生的事情?

非常感谢

Versions used:
    Grails 2.5.6
    GORM 3.1.4 
    Spring 4.1.9
    Hibernate3 3.6.10

1 个答案:

答案 0 :(得分:0)

您似乎正在尝试访问grails控制器/服务之外的实体上的getter。

如果您有懒惰的关系,并且想要访问它,那么您应该使用withTransaction关闭:

YourEntityClass.withTransaction{
    yourEntityClass.getX()
    // more logic
}

其他解决方法是:

  • 将您的逻辑保持在Service
  • 使用预先加载