Hibernate: Optimize updates with @DynamicUpdate

By | December 7, 2016

When using Hibernate as a layer between your Java code and the Database layer you release control on how the actual SQL query is generated. Hibernate will generate from the HSQL you write the “best” query. That “best” is in fact sometimes sub-optimal.
A very important Hibernate 4 (make sure you have at least 4.2.5) annotation that controls how an update behaves is @DynamicUpdate.
By default the Hibernate behaviour is to update all the fields of a an entity, so in fact @DynamicUpdate(false)

Take for example the following entity:

When I update the status of a list of objects of this type from READY to DELIVERED the update generated by Hibernate will update also the column holding the LOB. You can imagine the problem here if your LOB is on average 10MB and your update is done on 1000 objects.

After I add the annotation @DynamicUpdate(true) and I do the same update of the status the update generated by Hibernate will be:

This can have a huge difference in performance.

Advertisements