Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying object in AfterInsert / AfterUpdate

Tags:

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.

like image 605
Jean Barmash Avatar asked Mar 04 '10 20:03

Jean Barmash


2 Answers

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

like image 171
leebutts Avatar answered Oct 12 '22 14:10

leebutts


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

like image 31
fabien7474 Avatar answered Oct 12 '22 13:10

fabien7474