views:

44

answers:

2

Hi all

I have a grails service that is persisting some changes. If I rollback the transaction in the service class, throwing a RuntimeException, and later (in the same request) I try to re-read any data, I'm getting the following exception:

ERROR hibernate.LazyInitializationException  - failed to lazily initialize a collection of role: <my related class> no session or session was closed

So, the case is the following:

I try to update an object, in the service class, and if it fails, I will rollback the transaction. In the controller, take care of the exception, and I return an XML of the failed object. To create the XML grails is trying to read all related objects -lazy load 1-n relationship- (that is what I want), but as we already did a rollback in the service class, I have no session, and it fails. I tried using .withNewSession {} and it does not work.

Any ideas or workaround?

+1  A: 

It seems that you have Detached Object so try to use merge() method.

Olexandr
Well, actually I try to read other object... so seems it is not my case. :-(
Juan Garcia
+1  A: 

First of all, are you manually dealing with the transactions (it sounds like it from your post)? Grails will do that for you if you make the service transactional. I would recommend against trying to manage the tx yourself if that is indeed what you are doing. Stuff like that is complicated and error prone, and if Grails does it for your, why would you do that to yourself?

Second, it sounds like in the case of error, you are trying to access data that was loaded. Since your session went away when the tx rolled back, you can't do that. I would change your error message to not rely on any data in the session, if possible. i.e. dont try to xml-ify the object.

Although, I am not sure why the withNewSession is not working... Can we see some code?

hvgotcodes
Hi,The code is something like this (simplified)try { myService.updateObject (myObject)}catch (Exception e){ //upps we got a runtiome exception. Then tx is relledback. Let's return the object back to the client with validation errors render myObject as XML //<- Here I got the lazy init exception, because there are relations still not loaded that the marshaller will try to load}....
Juan Garcia
so back to the detached objects :) - myObject (or some of it's relations) is belongs to rolled back transaction(closed session) so you have to merge it to current session.
Olexandr
Now I understand what you say. Thanks so much for your help
Juan Garcia