我在Grails中的withSession和当前的hibernate会话之间感到困惑。
我的问题是:我们在闭包中访问的会话对象是否与当前的hibernate会话对象相同?
我写了一个服务 ,其行为如下:
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 = [Coll ......“
I am confused between withSession in Grails and current hibernate session.
My question is: Is the session object which we have access to in the closure the same as the current hibernate session object?
I wrote a Service that has an action as below:
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() } }What is strange for me is that there are 5 different hash codes... If I print the 5 session objects, I see the same toString() result. That makes me guess that they have the same contents:
SessionImpl(PersistenceContext[entityKeys=[EntityKey[com.astek.agileFactory.Link#170], EntityKey[com.astek.agileFactory.Project#9]],collectionKeys=[Coll......"
最满意答案
简要回答你的问题: 我们在闭包中访问的会话对象不是当前的hibernate会话。
会话对象是当前hibernate会话的代理。 因此在每种情况下都有不同的哈希码
看一下withSession的来源 ,清楚地看到setExposeNativeSession在HibernateTemplate中设置为false (默认值也是false),它确保始终返回Session Proxy而不暴露本机hibernate会话。
To answer your question briefly: The session object which we have access to in closure is not the current hibernate session.
The session object is a proxy of the current hibernate session. Hence different hash codes in each case.
Have a look at source of withSession, clearly seen setExposeNativeSession is set to false (default value is false as well) in HibernateTemplate which makes sure to always return a Session Proxy without exposing the native hibernate session.
更多推荐
发布评论