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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With