0 votes
in JAVA by
What is difference between Hibernate save(), saveOrUpdate() and persist() methods?

1 Answer

0 votes
by

Hibernate save() method can be used to save entities to the database. The problem with the save() method is that it can be invoked without a transaction and if we have mapping entities, then only the primary object gets saved causing data inconsistencies. Also, save returns the generated id immediately.

Hibernate persist() method is similar to the save() method with a transaction. It’s better to use persist() method than the save() method because we can’t use it outside the boundary of a transaction, so all the object mappings are preserved. Also, persist() method doesn’t return the generated id immediately, so data persistence happens when needed.

Hibernate saveOrUpdate() method results into insert or update queries based on the provided data. If the data is present in the database, the update query is executed. We can use saveOrUpdate() without transaction also, but again you will face the issues with mapped objects not getting saved if a session is not flushed.

...