Share on Google+Share on Google+

Hibernate : Dynamic-insert

This tutorial contains description of Hibernate dynamic-insert.

Hibernate : Dynamic-insert

This tutorial contains description of Hibernate dynamic-insert.

Hibernate : Dynamic-insert :

Hibernate allows you to use dynamic-insert. It is optional and by default it's value is false.
When dynamic-insert is true it means INSERT SQL is generated at runtime and contains only those columns whose value are set.
Hibernate generates corresponding SQL each time for dynamic-insert.
It is good to use dynamic-insert or dynamic-update where number of columns in a table and you want to set value in some of them.

You can use dynamic-insert in two ways -by using annotation or in xml file.

Example - Here is an example of dynamic-insert. We are using annotation to set dynamic-insert. -

package net.roseindia.table;


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

dynamicInsert = true)                //
public class Student implements Serializable {

private int roll;

private String name;

private String course;

public Student() {


public int getRoll() {
return roll;

public void setRoll(int roll) {
this.roll = roll;

public String getName() {
return name;

public void setName(String name) { = name;

public String getCourse() {
return course;

public void setCourse(String course) {
this.course = course;


Main class

package net.roseindia.main;

import net.roseindia.table.Student;
import net.roseindia.util.HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class HibernateDynamicInsert {

public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Student student = new Student();
System.out.println("Record saved");
} catch (HibernateException e) {
} finally {

Output :

Hibernate: insert into student (name) values (?)
Record saved

If you assign dynamicInsert =false then your output is -

Hibernate: insert into student (course, name) values (?, ?)
Record saved

Click here to download complete source code


Posted on: August 17, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Hibernate : Dynamic-insert  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image