【问题标题】:grails withSession and current hibernate sessiongrails withSession 和当前休眠会话
【发布时间】:2013-05-18 14:49:20
【问题描述】:

我对 Grails 中的 withSession 和当前休眠会话感到困惑。

我的问题是:我们在闭包中可以访问的会话对象是否与当前休眠会话对象相同?

我写了一个Service,其动作如下:

def strangeBehavior(){

    Link.withSession { session->
        println "link current session " +  session.hashCode()
    }

    Task.withSession { session->
        println "task current session " +  session.hashCode()
    }

    Project.withSession { session->
        println "project current session " +  session.hashCode()
    }

    UserStory.withSession { session->
        println "user story current session " +  session.hashCode()
    }

    def ctx = AH.application.mainContext
        def sessionFactory = ctx.sessionFactory
        def tmp = sessionFactory.currentSession
        println " current session " +  tmp.hashCode()
    }
}

对我来说奇怪的是有 5 个不同的哈希码...如果我打印 5 个会话对象,我会看到相同的 toString() 结果。这让我猜测它们具有相同的内容:

SessionImpl(PersistenceContext[entityKeys=[EntityKey[com.astek.agileFactory.Link#170], EntityKey[com.astek.agileFactory.Project#9]],collectionKeys=[Col……”

【问题讨论】:

  • 不,抱歉让你混淆了,事实上,我刚刚写了一个普通的服务,它有一个名为strangeBehavioi()的动作,我用run-app运行我的应用程序。

标签: hibernate session grails


【解决方案1】:

简要回答您的问题:
我们在关闭时可以访问的会话对象不是当前的休眠会话。

会话对象是当前休眠会话的代理。因此在每种情况下都有不同的哈希码。

看一下source of withSession,可以清楚地看到setExposeNativeSessionHibernateTemplate 中设置为false(默认值也是false),这确保始终返回会话代理而不暴露本机休眠会话。

【讨论】:

  • 感谢 dmahapatro !查看源代码确实是澄清问题的好主意,您的解释很简单但很有帮助
  • @Greedydp ..如果它有帮助,您可以通过接受它来使答案变得强大。 :)
猜你喜欢
  • 2015-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-20
  • 2012-05-05
  • 2014-11-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多