In this post, we will discuss the difference between Session.save() and Session.saveOrUpdate() method in Hibernate with an example.
Learn the Hibernate ORM framework at https://www.javaguides.net/p/hibernate-tutorial.html
Hibernate - difference between Session.save() and Session.saveOrUpdate() method
- The main difference between Session.save() and Session.saveOrUpdate() method is that save() generates a new identifier and INSERT record into a database while Session.saveOrUpdate() can either INSERT or UPDATE based upon existence of a record. Clearly, saveOrUpdate() is more flexible in terms of use but it involves extra processing to find out whether a record already exists in the table or not.
Session.save() method example: The below code uses Session.save() method to insert a new record into a database:
public void saveExample(Student student) {
Transaction transaction = null;
try (Session session = HibernateJavaConfig.getSessionfactory().openSession()) {
// start the transaction
transaction = session.beginTransaction();
// save student entity
Serializable id = session.save(student);
System.out.println("database table id -> " + id);
// commit transaction
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
}
}
Session.saveOrUpdate() method example: The below code uses Session.saveOrUpdate() method INSERT or UPDATE a record based on the existence of the record in a database.
public void saveOrUpdateExample(Student student) {
Transaction transaction = null;
try(Session session = HibernateJavaConfig.getSessionfactory().openSession()){
// start the transaction
transaction = session.beginTransaction();
// first save student entity using saveOrUpdate() method
session.saveOrUpdate(student);
// get the student object
Student student2 = session.get(Student.class, student.getId());
// update the student2 object
student2.setFirstName("Prabhas");
student2.setEmail("prabhas@gmail.com");
// update student entity using saveOrUpdate() method
session.saveOrUpdate(student2);
// commit transaction
transaction.commit();
}catch (Exception e) {
if(transaction != null) {
transaction.rollback();
}
}
- The return type of the Session.save() method is java.io.Serializable. It returns the newly generated identifier id value as a Serializable object. While return type of the Session.saveOrUpdate() method is void (does not return anything).
Here are the return types of these methods from the Java API doc.
Session.save() method:
Serializable org.hibernate.Session.save(Object object)
Session.persist() method:
void org.hibernate.Session.saveOrUpdate(Object object)
Video
The below video explained the difference between save() and saveOrUpdate() method in Hibernate with a coding example:
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course