I have a Grails application (2.5.4) deployed on production which receives a large amounts of traffic.
We are getting intermittent LazyInitializationException
exceptions when trying to access fields from domain objects that are stored in the session.
To clarify how the flow works:
We have a filter (http://docs.grails.org/2.5.4/ref/Plug-ins/filters.html) that gets called before each controller action. In this filter we store a domain object in the session (http://docs.grails.org/2.5.4/ref/Servlet%20API/session.html) like this:
session.account = Account.get(1)
In the controller, we retrieve the Domain like this:
def account = session.account
We then pass the domain object to another service, which calls another service which eventually tries to call a hasMany field on the domain object like this:
account.transactions.name
The above throws a LazyInitializationException
with a message similar to this:
failed to lazily initialize a collection of role: com.example.app.Account.transactions, no session or session was closed
So for some reason the Hibernate session is being closed before the request is finished, hence the lazy load exception.
We found doing the following in the controller completely eliminates the error from occurring:
Account account = Account.findById(session.account.id)
The problem is, I have no idea why and would like to understand why this fixes the issue before blindly implementing this fix in other parts of the application. I see no reason why the object should become detached from the Hibernate Session as this flow is all occurring within the same request. On top of this, it is a very random problem - it occurs maybe 1% of the time the request is made, if not less.
To clarify, the question is; Why is the session being closed and why is the object becoming detached from the Hibernate Session when its all happening within the same request scope? Also, why it does it only happen very rarely and randomly?