understanding withNewSession in Grails

风流意气都作罢 提交于 2020-01-04 04:46:10

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/32328150/understanding-withnewsession-in-grails

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!