Home  >  Hibernate

Hibernate Session: save(), update() and saveOrUpdate() Example

By Arvind Rai, February 14, 2015
In this page we will learn the use and differences of save(), update() and saveOrUpdate() methods of hibernate Session object. save() method runs the insert query, update() method runs the update query and saveOrUpdate() method first run the select query and then run insert or update query depending on data exist in database or not against given identifier. save() method also returns the generated identifier.

Session.save()

save() method saves the transient entity. Before saving, it generates identifier . The associated instances are also persisted if cascade is defined as "save-update". There are two overloading function of this method.

save(Object object) : Accepts instance of Entity to save.
save(String entityName, Object object) : Accepts entity name and instance of entity.

Find the sample example.
SaveMethodDemo.java
package com.concretepage;
import org.hibernate.Session;
public class SaveMethodDemo {
	public static void main(String[] args) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Student s = new Student(1, 22,"Ram");
		session.beginTransaction();
		Integer i = (Integer)session.save(s);
		System.out.println("Generated Identifier:"+ i);
		session.getTransaction().commit();
		session.close();
	}
} 
And find the output.
Generated Identifier:1
Hibernate: insert into student (age, name, id) values (?, ?, ?) 
Look at the output. save() method first generates identifier and then inserts data into database. We can see the insert query in the output.

Session.update()

update() method updates the entity for persistence using the identifier of detached object or new instance of entity created with existing identifier. If the object is already in the session with the same identifier, then it throws exception. This method updates the associated object if cascade is defined as "save-update".

update(Object object) : Accepts the instance of new entity or any detached object from the session.
update(String entityName, Object object) : Accepts the entity name and instance of object.

Find the sample example.
UpdateMethodDemo.java
package com.concretepage;
import org.hibernate.Session;
public class UpdateMethodDemo {
	public static void main(String[] args) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Student s = new Student(1, 22,"Mahesh");
		session.beginTransaction();
		session.update(s);
		session.getTransaction().commit();
		session.close();
	}
} 
And find the output.
Hibernate: update student set age=?, name=? where id=? 
update() method runs the update query against the identifier.

Session.saveOrUpdate()

saveOrUpdate() method of Session class works as save() or update() method. First hibernate checks the existence of instance of entity and if not available then inserts the data into database and if available then updates the data. The associated objects are also persisted or updated if cascade is defined as "save-update".

saveOrUpdate(Object object): Accepts the instance of new entity or any detached object from the session to save or update.
saveOrUpdate(String entityName, Object object): Accepts the entity name and instance of object.

Find the sample example.
SaveOrUpdateMethodDemo.java
package com.concretepage;
import org.hibernate.Session;
public class SaveOrUpdateMethodDemo {
	public static void main(String[] args) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Student s = new Student(1, 25,"Ram");
		session.beginTransaction();
		session.saveOrUpdate(s);
		session.getTransaction().commit();
		session.close();
	}
} 
And find the output.
Hibernate: select student_.id, student_.age as age2_0_, student_.name as name3_0_ from student student_ where student_.id=?
Hibernate: insert into student (age, name, id) values (?, ?, ?) 
The above output shows that the entity with specified identifier does not exist in database by running select query. So it applied insert query to persist data. Now check the output for such situation where entity for the given identifier is already there in database.
Hibernate: select student_.id, student_.age as age2_0_, student_.name as name3_0_ from student student_ where student_.id=?
Hibernate: update student set age=?, name=? where id=? 
Here first select query runs to check existence of data for given identifier and since data is there, so update query runs to update data.

Entity

Find the Entity being used in the example.
Student.java
package com.concretepage;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="student")
public class Student {
	@Id
	@Column(name="id")
	private int id;
	@Column(name="age")
	private int age;
	@Column(name="name")
	private String name;
	public Student(){}
	public Student(int id, int age, String name){
		this.id = id;
		this.age = age;
		this.name = name;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
} 
Now we are done. Happy learning.

Download Complete Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS
comments powered by Disqus








Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us