1

I have two entities ENTA having one-many relationship with ENTB.

I am trying to update two records in java. The order of updates that is happening is :

update ENTA set column_name=? where id=ENTA1;
update ENTB set column_name=? where id=ENTB1;
update ENTB set column_name=? where id=ENTB2;
update ENTA set column_name=? where id=ENTA2;

My problem is on update of ENTB, we have a Database trigger which calculates the value for one of the column of ENTA table.

Hence for the first record, the update happens correctly. However for the second record, the update by the trigger is overridden since the order of updates has changed for the second records as seen above.

I tried to do dynamic-update="true" for ENTA table, however some other areas in my application are not working as per expected.

I have even tried for order_updates property of hibernate, however no success!

Could you please let me know any other way to tell hibernate to update it in a particular order?

Dragan Bozanovic
  • 23,102
  • 5
  • 43
  • 110

1 Answers1

2

Take a look at this answer. Basically, the strict order of updates is not defined in Hibernate. It happens that the current implementation uses the order in which entities are added/loaded into the session (persistence context).

The reason behind this is that Hibernate sees what's changed at dirty-check time, when it compares the current state of the objects with the snapshot that it stored when objects are added to the session. Hibernate has no idea in which order you changed the objects before dirty-check is executed.

The purpose of hibernate.order_updates is to make batching of update statements more efficient (more details in this blog), but is not related to your issue.

The solution is to manually flush the session after you change the objects which you want to be updated first, but before you change other objects. For example, suppose that you want the changes of entity A be synchronized before the changes to entity B. The order of actions should be the following:

  1. Change instance A.
  2. Flush the session. This executes update statement for A.
  3. Change instance B.
Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
Dragan Bozanovic
  • 23,102
  • 5
  • 43
  • 110