[Hibernate] – Increase performance using @DynamicUpdate or @DynamicInsert

When you change only the value of a single attribute of an object we know that Hibernate makes an update query with all attributes and their respective values.

Example of scenario:

client.name = “new name”;

em.merge(client);

Query

update Client 
    set name=?, 
    address=?, 
    code=?, 
    document=?, 
    observations=?, 
    version=? 
where id=? and version=?

How to make a query only with the changed values ?

The @DynamicUpdate annotation allows them to be in the query only the fields that have changed. In this case, the update query will be:

update Client set name=? where id=?

How to do it ? 

@Entity
@Table(name = "client", catalog = "example")
@org.hibernate.annotations.Entity(
		dynamicUpdate = true
)
public class Client implements java.io.Serializable {

Also you can do this by xml file configuration

<class ... table="client" catalog="example" dynamic-update="true">
        <id name="tranId" type="java.lang.Integer">
            <column name="TRAN_ID" />
            <generator class="identity" />
        </id>

You also can use @DynamicInsert, too.

It works in the same way.

IMPORTANT : Don’t use it in all cases ! Think First!

This can improve the performance, mainly if you have a table with too many constraints or /and too many triggers. Updating only the affected columns will increase the performance. However, for the Hibernate makes a dynamic query has cost. So, you need measure in each case.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s