Hibernate dynamic-insert attriburte example

This tutorial shows how to use the dynamic-insert attribute or @DynamicInsert annotation used by Hibernate. This attribute/annotation tells Hibernate whether to include null properties in the SQL INSERT statement.

Dynamic-insert=false

By default, dynamic-insert is set to false. Which means all properties are included in the SQL INSERT statement.

For example, we have an Event object which only contains a name.

Event event = new Event();
event.setName("Hibernate dynamic-insert - @DynamicInsert - example");
event.setLocation(null);
event.setDate(null);
em.persist(event);

Hibernate executes the following query.

Hibernate: 
    insert 
    into
        Event
        (date, location, name) 
    values
        (?, ?, ?)

Note: Hibernate includes all properties in the SQL Statement.

Dynamic-insert=true

When we set the dynamic-insert attribute to true, Hibernate will generate a SQL INSERT without null values.

For example, we have an Event object which only contains a name.

Event event = new Event();
event.setName("Hibernate dynamic-insert - @DynamicInsert - example");
event.setLocation(null);
event.setDate(null);
em.persist(event);

Hibernate executes the following query.

Hibernate: 
    insert 
    into
        Event
        (name) 
    values
        (?)

Note: Hibernate includes only not-null properties in the SQL Statement.

What about performance?

Let’s talk about performance, because you must be thinking that dynamic-insert 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-insert, 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-insert on a – per entity basis – using either the @DynamicInsert annotation or the dynamic-insert XML Mapping attribute.

Annotation Mapping

import org.hibernate.annotations.DynamicInsert;

@Entity
@DynamicInsert
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-insert="true">

        ...

    </class>
</hibernate-mapping>

References

Download

You may also like...