Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understanding withNewSession in Grails

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!

like image 923
kofhearts Avatar asked Sep 01 '15 09:09

kofhearts


1 Answers

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.

like image 76
kofhearts Avatar answered Oct 24 '22 07:10

kofhearts