Blog

Wednesday, 15 January 2014

Hibernate, triggers and yo-yo update

While using Hibernate to manage DB operations in your application you may also need to use triggers to perform specific updates directly inside DB. But if you're using both update methods it's essential to protect yourself against yo-yo effect.

What do I mean by 'yo-yo' effect? It's a situation when Hibernate inserts/updates are followed be some more inserts/updates executed on the same table. This usually happens if entities in your data model reference each other in a complicated (or even circular) manner and you also have cascade updates defined for some of those references. When you have a trigger installed on the very same table, it is possible that second set of changes will override updates made by the trigger function. On the first sight it may look like trigger is not working at all.

I had exactly such situation today. What was even more strange was that everything worked fine on my localhost. But in production environment the trigger seemed not to be firing. Apparently there was a difference in the order in which insert/update queries were executed in both environments. The solution to the problem was pretty simple. Fields which are updated by the trigger should be declared as not updatable nor insertable in entity classes:

@Entity
public class User implements Serializable {

   @Column(name = "ACCOUNT_EXPIRATION_DATE", insertable = false, updatable = false)
   private Date accoutExpirationDate;

   ...

}

No comments:

Post a Comment