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.

Contribute to this site maintenance !

This is a self hosted site, on own hardware and Internet connection. The old, down to earth way 🙂. If you think that you found something useful here please contribute. Choose the form below (default 1 EUR) or donate using Bitcoin (default 0.0001 BTC) using the QR code. Thank you !

€1,00

Advertisements

2 thoughts on “Hibernate: Optimize updates with @DynamicUpdate

  1. George Valentin Voina Post author

    From, what I know this annotation is an Entity attribute: In fact the following annotations are Entity attributes.
    @SelectBeforeUpdate
    @DynamicInsert
    @DynamicUpdate
    @Polymorphism
    @OptimisticLocking

    So, being Entity attributes I am assuming that they are Entity specific so they are not inherited. My guess is that you will have to define them for each Entity.
    See: https://howtodoinjava.com/hibernate/hibernate-jpa-2-persistence-annotations-tutorial/

    Reply
  2. Shy

    Is @DynamicUpdate inheritable? Like if my Entity class extends to a super class and I added the annotation on my super class alone. Would it work?

    Reply

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.