Hibernate Dynamic-Update Attriburte Example
This tutorial shows how to use the dynamic-update attribute or @DynamicUpdate annotation used by Hibernate. This attribute/annotation tells Hibernate to only include the updated properties of the entity in the SQL UPDATE Statement.
Dynamic-update=false
By default, dynamic-update is set to false. Which means all properties are included in the SQL UPDATE statement.
For example, suppose we have an existing Event object which we want to modify. We modify only the name.
Event updateEvent = em.find(Event.class, 1); updateEvent.setName("Hibernate dynamic-update - @DynamicUpdate - example"); em.persist(event);
Hibernate executes the following query.
Hibernate: update Event set name=?, location=?, date=? where id=?
Note: Hibernate includes all properties in the SQL UPDATE Statement.
Dynamic-update=true
When we set the dynamic-update attribute to true, Hibernate will generate a SQL UPDATE with only the modified properties.
For example, suppose we have an existing Event object which we want to modify. We modify only the name.
Event updateEvent = em.find(Event.class, 1); updateEvent.setLocation("Hibernate dynamic-update - @DynamicUpdate - example"); em.persist(event);
Hibernate executes the following query.
Hibernate: update Event set location=? where id=?
Note: Hibernate includes only modified properties in the SQL Statement.
What about performance?
Let’s talk about performance, because you must be thinking that dynamic-update is always the way to go, right? This is not the case.
Hibernate caches the actual SELECT, INSERT and UPDATE SQL strings for each entity. This results in not having to re-create these statements every time you want to find, persist or update an entity.
However, when using dynamic-update, Hibernate has to generate the corresponding SQL strings each time. This results in a performance cost on the Hibernate side. In other words, there is a trade-off between overhead on the database side and on the Hibernate side.
Configuration
You can configure the dynamic-update on a – per entity basis – using either the @DynamicUpdate annotation or the dynamic-update XML Mapping attribute.
Annotation Mappingimport org.hibernate.annotations.DynamicUpdate;
@Entity
@DynamicUpdate
public class Event implements Serializable {
...
}
XML Mapping
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.memorynotfound.hibernate.Event" dynamic-update="true">
...
</class>
</hibernate-mapping>
Download
Download it – hibernate-dynamic-update-attribute-example
From:一号门
Previous:JPA EntityManager Example
COMMENTS