Hibernate save Example - Rose India Hibernate 4 tutorials

In this section we will learn how to perform the save operation on the entity object. This example will teach you how to use the Session.save() method to save an object to the database using the Hibernate 4 framework

Hibernate save Example - Rose India Hibernate 4 tutorials

Hibernate save Example - Rose India Hibernate 4 tutorials

In the last section you have learned how to create Hibernate application in Eclipse. We have also saved the object using the Session.save() method. Here in this section we will explain you about the Session object and its methods.

Download the source code of the example discussed here from First Hibernate Example Step by Step in Eclipse tutorial page.

How to save objects in Hibernate?

Hibernate is very easy tool for creating the database access code. Developers interacts with the runtime through Session interface. The Session interface is the main interface between Java applications and Hibernate runtime. The Session interface provides the methods for saving, querying, updating and deleting the data from the database.

Here are the methods of the Session interface of Hibernate:

  • save() - Used to save the object
  • update() - Updated the state of object in database
  • delete() - Delete from underlying database
  • createCriteria(String entityName)  - For selecting data based on certain criteria

The Session interface is retrieved using following code:

Session session = sessionFactory.openSession();

Transaction Management

You can also start the transaction using following code:


Here is the code for transaction management:

Session sess = factory.openSession();
 Transaction tx;
 try {
     tx = sess.beginTransaction();
     //do some work
 catch (Exception e) {
     if (tx!=null) tx.rollback();
     throw e;
 finally {

Here is the complete code for saving the data in Hibernate based application:

package net.roseindia;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import net.roseindia.model.*;
 * @author Deepak Kumar 
 * Web: http://www.roseindia.net
public class CreateData {
	public static void main(String[] args) throws Exception {

		SessionFactory sessFact = HibernateUtil.getSessionFactory();
		Session session = sessFact.getCurrentSession();
		org.hibernate.Transaction tr = session.beginTransaction();
		Employee emp = new Employee();
		emp.setEmpName("Deepak Kumar");
		emp.setEmpAddress("Delhi - India");
		System.out.println("Successfully inserted");


Above class creates the object of Employee entity, sets the values and finally calls the session.save(emp)  to save the data.

Here is the code of the model class used in the example:

package net.roseindia.model;
import java.io.Serializable;

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

import javax.persistence.Table;
 * @author Deepak Kumar
 * Web: http://www.roseindia.net
@Table(name = "employee")
public class Employee implements Serializable{

	private int id;	

	private String empName;

	private String empAddress;	  

	private String empMobileNos;

	public int getId() {
		return id;

	public void setId(int id) {
		this.id = id;

	public String getEmpName() {
		return empName;

	public void setEmpName(String empName) {
		this.empName = empName;

	public String getEmpAddress() {
		return empAddress;

	public void setEmpAddress(String empAddress) {
		this.empAddress = empAddress;

	public String getEmpMobileNos() {
		return empMobileNos;

	public void setEmpMobileNos(String empMobileNos) {
		this.empMobileNos = empMobileNos;


The code of hibernate.cfg.xml file used in the project:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"

<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate4</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>

<mapping class="net.roseindia.model.Employee" />


Here is the code of utility class which contains a method to get the SessionFactory:

package net.roseindia;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

 * @author Deepak Kumar 
 * Web: http://www.roseindia.net
public class HibernateUtil {
	private static final SessionFactory sessionFactory;

	private static ServiceRegistry serviceRegistry;

	static {

		try {

			Configuration configuration = new Configuration();
			serviceRegistry = new ServiceRegistryBuilder().applySettings(
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);

		} catch (Throwable th) {

			System.err.println("Enitial SessionFactory creation failed" + th);

			throw new ExceptionInInitializerError(th);



	public static SessionFactory getSessionFactory() {

		return sessionFactory;


In this you have learned how to use Hibernate's session.save() method to save the data in our example program.

Download the Source code of the project discussed here.

Check more Hibernate 4.2 tutorials.