Hello All,

Welcome back to Hibernate series. Today we are are going to discuss about save() and persist() in hibernate. It’s really imperative to know this topic.

Difference between save() and persist() method.

save() :-

  • This method is used to save an entity or object into the database and returns generated the primary key. It will throw an exception if an entity already exists in the database.
  • The return type of the save method is java.io.serializable. it returns the generated primaray key immediately.
  • It can be used inside or outside the transction boundaries.
  • It is hibernate specific method so we can’t use another JPA specific implementation.
  • It takes more time to compare than persist() method to execute so it is slow in execution.
  • It is the overloaded method so we can use the save() method in two way:-

 

Example:- 

persist() :-

  • This method is used to save an entity or object into the database and return void. It will throw an exception if an entity already exists in the database.
  • It is the JPA specific method so it is available all the JPA specification implementation.
  • The return type of the persist() method is void.
  • It can be use only inside the transction boundaries.
  • It takes less time compare than save() method to execute so it is fast in execution.

Example:- 

 

Thanks to all.