Thursday, 18 April 2019

Difference between session.save() , session.saveOrUpdate() and session.persist()?

session.save() : Save does an insert and will fail if the primary key is already persistent.

session.saveOrUpdate() : saveOrUpdate does a select first to determine if it needs to do an insert or an update.

Insert data if primary key not exist otherwise update data.

session.persist() : Does the same like session.save().

But session.save() return Serializable object but session.persist() return void.



         session.save() returns the generated identifier (Serializable object) and session.persist() doesn't.
For Example :
         if you do :-
         System.out.println(session.save(question));
         This will print the generated primary key.
         if you do :-
         System.out.println(session.persist(question));
         Compile time error because session.persist() return void.


1) The main difference between save() and saveOrUpdate() method is that save() method performs an INSERT operation to store the object into the database, but INSERT will fail if the primary key is already persistent i.e. object already exists in the database. This is why, you should only call save() with an absolutely new object which doesn't have any database identifier. Calling save() with the detached object will fail. This is opposite of saveOrUpdate() method, which can do either INSERT or UPDATE SQL query depending upon whether an object exists in the database or not. The saveOrUpdate() method first executes a SELECT query to determine if it needs to do an INSERT or UPDATE operation.


2) Another key difference between save() and saveOrUpdate() method is that former is used to bring a transient object to persistent state but saveOurUpdate() can bring both transient (new) and detached (existing) object into persistent state. It is often used to re-attach a detached object into Session.


3) Coming to persist() method, the difference between save() and persist() method is that former returns the generated database identifier, a Serializable object but persist() method doesn't return anything. It's return type is void.

For example:

System.out.println(session.save(aCoin));

will print the generated primary key, but the following line will throw a compile time error because persist()'s return type is void.

System.out.println(session.persist(aCoin));

No comments:

Post a Comment

Spring Boot @ConfigurationProperties and Properties File

 In this tutorial, you will learn to use @ConfigurationProperties to map properties files to POJO classes in Spring Boot application. Let’s ...