了解Grails中的新会话 [英] understanding withNewSession in Grails
问题描述
首先,Grails的文档用NewSession解释如下:
https://grails.github.io/grails -doc / latest / ref / Domain%20Classes / withNewSession.html
Defn:提供一种执行方式代码在新的Hibernate会话的上下文中,该会话与当前绑定的会话共享相同的事务(JDBC连接)资源。
我是中级grails用户,所以我不是虽然我理解Grails是如何使用会话的,但对上述定义感到满意。你能提供一个例子解释使用
Domain.withNewSession {session - >
// do work
}
我会很感激!我很快就回到我自己的问题,我发布了答案,我得到了任何人可能会发现这个问题的解决方案。有用。
以下是一个简单的例子,可以用来理解NewSession。
def c = null
Event.withNewSession {
c = Event .first()
}
c.name =Test
println c.save()
上面的代码会导致异常。 c是一个域对象,但是因为它是在一个newsession块中查询的,所以它只与这个新会话相关联。
抛出的异常是:
org.hibernate.LazyInitializationException:could不初始化代理 - 没有会话
这是为什么.save()调用。
def c = null
Event.withNewSession {
c = Event .first()
}
println c.isAttached()
得到的结果是
false
因此,您可以看到该域与旧会话分离。这是一种新的用法。 Withnewsession将创建一个新会话,以便在withnewsession块中查询的任何域将仅附加到此新会话,并在退出newsession块后分离。
First of all the documentation of grails explains withNewSession as follows:
https://grails.github.io/grails-doc/latest/ref/Domain%20Classes/withNewSession.html
Defn: Provides a way to execute code within the context of a new Hibernate session which shares the same transactional (JDBC Connection) resource as the currently bound session.
I am an intermediate grails user so i am not comfortable with the above definition although i understand how grails make use of sessions. Can you provide an example that explains the use of
Domain.withNewSession { session ->
// do work
}
I will appreciate a lot!
Ok i am coming back to my own question after a long time and i am posting the answer i got for anyone who might find this useful.
Here is a simple example to understand withNewSession.
def c = null
Event.withNewSession{
c = Event.first()
}
c.name = "Test"
println c.save()
The above code will cause an exception. c is a domain object but since it was queried inside a newsession block it is only associated with this new session.
The thrown exception is
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
Here is the reason why the exception was thrown when .save() was called.
def c = null
Event.withNewSession{
c = Event.first()
}
println c.isAttached()
The output got is
false
So, you can see the domain was detached from old session. This is one usage of withnewsession. Withnewsession will create a new session so any domains that were queried inside the withnewsession block will be only attached to this new session and will be detached after exiting the newsession block.
这篇关于了解Grails中的新会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!