tags:

views:

81

answers:

3

I have a domain object that holds results of a calculation based on parameters that are properties of the same domain object. I'd like to make sure that any time parameters get changed by the user, it recalculates and gets saved properly into the database.

I am trying to do that with afterInsert (to make sure calculation is correct in the first place), and afterUpdate.

However, since my calculation is trying to modify the object itself, it's not working - throwing various hibernate exceptions.

I tried to put the afterUpdate code into a transaction, but that didn't help. I am afraid I am getting into a circular dependency issues here.

The exception I am getting right now is:

org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [esc.scorecard.PropertyScorecard#27]

Are the GORM events designed for simpler use cases? I am tempted to conclude that modifying the object you are in the middle of saving is not the way to go.

+1  A: 

Is there any reason against using beforeInsert and beforeUpdate instead of afterInsert and afterUpdate?

If not, switching to the before* event handlers should fix your issue

fabien7474
I thought by the time afterInsert fires, the object is almost persisted, and has an id by that point, but I might be wrong - the whole persistence process (with events) doesn't seem to be well-documented.
Jean Barmash
Indeed, if your calculation is using the 'id' property, it might be a problem to locate your code into before* handlers. And I don't know which event is fired when id is generated.
fabien7474
+1  A: 

Are you using 1.2.0+?

If you are, you can use .withNewSession in the events closures which is supposed to avoid hibernate chaos.

cheers

Lee

leebutts
yes, i am on 1.2.1. I tried using withNewSession, but that didn't help, resulting in weird hibernate errors.
Jean Barmash
A: 

hi jean... what's your workaround with this problem. I am also facing this dilemma. .withNewSession doesn't seem to work for afterInsert. I can't flush the object nor just save it (well i can .save() but it seems that the calculations I've done inside the afterInsert are not persisted in the database if I just use .save() ). thanks!

Anyway what I just want to do is to persist a User object inside of my domain class (eg., Message) who created it. Since audit-trail just saves a Long reference only (eg., createdby), I can't eventually manipulate the Message domain class and eventually reference its attribute (eg., creator) as a User object. So I am thinking of manually stamping/ saving the User who is logged in to be the creator of that Message domain class. So Im trying to use the afterInsert event so I can manually save the creator eventually... There.

I'm new to this grails and its plugins so I am not sure what is the best practice to solve my problem. There you go. As of now I'm still figuring out how to use these GORM events

inquirer