Hibernate save or update method example

The saveOrUpdate() method is used to save or update the entity state to the database. In this tutorial you will learn the use the this method.

Hibernate save or update method example

Hibernate save or update method example

This tutorial is an example of loading the object from the database and then changing the state of the object. Finally saving the object into database using the  saveOrUpdate() method of the Session object.

The Hibernate's saveOrUpdate method is very useful it inserts the new record in the database if the entity is new. If the entity is old (already exists in database) then updates the modified value into the table.

The saveOrUpdate() method of the Session object works in the following way:

  • If the instance of object already in the database and there is not change then it does not un-necessary database call
  • If another object with same primary key exists then it throws exception
  • If the primay key of the object is null then it saves the data
  • It detects if the primary key assigned is new instance then save
  • It detects the change in the state of the object and senses decides on the object saving.

Following is the code of saveOrUpdate() method:

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 SaveOrUpdateExample {
	public static void main(String[] args) throws Exception {

		SessionFactory sessFact = HibernateUtil.getSessionFactory();
		Session session = sessFact.getCurrentSession();
		org.hibernate.Transaction tr = session.beginTransaction();
		Employee emp = (Employee)session.load(Employee.class, 1);
		emp.setEmpAddress("New Delhi, India");
		System.out.println("Data Updated");

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 section you have learned how to use the saveOrUpdate() method.

Download the Source code of the project discussed here.

Check more Hibernate 4.2 tutorials.