Tuesday, February 23, 2010

Hibernate update and dynamic-update

Introduction:

When we start working on hibernate we always get confused with some properties and their behavior. This write up explains the difference between two such properties that are used for table update.

update="false" and dynamic-update="true"

There are two scenarios with respect to hibernate update functionality.
1. One scenario is that we never want to update some fields. We just need to retain the value that was created originally. In such cases we have to set update="false" in hibernate mapping file as mentioned below.

<property name=”xxx” column=”xxx” update=”false”>

Practical usage of this could be, for example consider the following entity

public class User{
Integer userId;
String firstName;
String lastName;
Date createDate;
String createdBy;
Date updateDate;
String updatedBy;
}

The "createDate" and "createdBy" fields should be set only for the first time when it is created. Any further updates to that row should not modify "createDate" and "createdBy" fields.

So the configuration for this is set update=”false” in user.hbm.xml file.

<property name="createDate" column="createDate" update="false">
<property name="createdBy" column="createdBy" update="false">

2. Second scenario is that when we call session.update() method it generates SQL update statement for all the fields of that entity. If we would like to have only the fields that we modify then we need to set dynamic-update="true" in hibernate mapping files.

For example:
Consider the values of a user table’s row
{
1,
"Joe",
"Tee",
16/10/2009,
"John",
17/10/2009,
"John"
}
And we are updating only the user name

User user = userDAO.get(1);
user.setFirstName("Bee");
userDAO.update(user);
And the update statement generated usually is

UPDATE USER SET first_name='Bee', last_name='Tee', update_date='17/10/2009', updated_by='John' WHERE user_id=1;

Though we modified only one field, all fields are getting populated in the update statement. Here USER table is small and the performance impact may be less, but if we consider production tables with huge number of columns this will have the biggest performance impact.

To improve the performance, the requirement here is that update statement should contain only the fields that are updated.

To do that we need to set

<class name="User" table="USER" dynamic-update="true">

Once the property is set the update statement that gets generated is

UPDATE user set first_name='Bee' WHERE user_id=1;

No comments:

Post a Comment