Hibernate Dynamic SQL Generation

By default, Hibernate creates SQL statements for each persistent class on startup.These statements are simple create, read, update, and delete operations for reading a single row, deleting a row, and so on.

In some situations, such as a legacy table with hundreds of columns where the SQL statements will be large for even the simplest operations (say, only one column needs updating), you have to turn off this startup SQL generation and switch to dynamic statements generated at runtime. An extremely large number of entities can also impact startup time, because Hibernate has to generate all SQL statements for CRUD upfront. Memory consumption for this query statement cache will also be high if a dozen statements must be cached for thousands of entities (this isn’t an issue, usually).

The default value of dynamic-insert and dynamic-update is false, which means include null properties in the Hibernate’s SQL INSERT and SQL UPDATE statement. The dynamic-insert attribute tells Hibernate whether to include null property values in an SQL INSERT, and the dynamic-update attribute tells Hibernate whether to include unmodified properties in the SQL UPDATE.

You can configure the dynamic-insert and dynamic-update properties value through Annotation or XML mapping file.

1. Annotation

@Table(name = "EMPLOYEE")
        dynamicInsert = true, dynamicUpdate = true
public class Employee {

2. XML Mapping

<class name="com.kruders.bean.Employee" table="EMPLOYEE" dynamic-insert="true"
    <id name="employeeId" type="int" column="employee_id">
        <generator class="native" />

No comments yet.

Leave a Reply