Hibernate: Optimize updates with @DynamicUpdate

By | June 29, 2018

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:

@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Table(name = "OutputBulkBuffer")
public class OutputBulkBuffer {
	 * Content of the byte message
	protected byte[] byteContent;
	@Column(length = 50)
	protected String status;
	public byte[] getByteContent() {
		return byteContent;
	public void setByteContent(byte[] byteContent) {
		this.byteContent = byteContent;
	public void setStatus(Status status) {
		if (status != null) {
			this.status = status.getName();
		} else {
			this.status = null;
	public void setStatus(String status) {
		this.status = status;

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.

update OutputBulkBuffer set byteContent=?, status=? where id=?

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

update OutputBulkBuffer set status=? where id=?

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 !


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.

    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/

  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?


Leave a Reply

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