Hibernate save() vs persist()

Session.save()

The session.save() method is used to save the transient object by assigning a generated value or using a current value of the identifier property. In other words, the save() method is used to insert an object in the database and returns a generated identifier. If the object already exists in the database, it will throw an exception. The save() method is available in the Session interface.

There are two save() methods available in Hibernate with different parameters. They are listed below:

  • save(Object object)
  • save(String entityName, Object object)

Both of the above methods perform the same functions.

How to use session.save()

Employee emp = new Employee();

//setters

session.save(emp);                                        //saves the object emp

Session.persist()

The session.persist() method is used to make a transient instance persistent. This operation cascades with the associated objects if mapped with cascade= "persist." In other words, the persist() method is used to persist an entity in the database and returns a void. If the object already exists in the database, it will throw an exception. The Session interface provides the persist() method.

There are two persist() methods available in Hibernate with different parameters. They are listed below:

  • persist(Object object)
  • persist(String entityName, Object object)

 Both of the above methods perform the same functions.

How to use session.persist()

Employee emp = new Employee();

//session

session.persist(emp);                                        //saves the object emp

Difference between save() and persist()

          Parameter                     save()                       Persist()
Return type The save() method is used to save the object in the database and returns a Serializable object. The persist() method is also used to save the object in the database, but it returns a void.
Support Only Hibernate supports the save() method. The Hibernate and JPA, both support the persist() method.
Boundaries There is no boundary of the transaction for the save() method as it returns an identifier so that an insert query is immediately executed to get the id. The persist() method must be called inside the transaction. It will not execute if called outside the transaction.
Assignment The save() method guarantees that the identifier value will be assigned to the persistent object immediately. The persist() method doesn’t guarantee that the identifier value will be assigned to the persistent object immediately. The assignment might be happening at the flush time.



ADVERTISEMENT
ADVERTISEMENT