What are the differences between the different saving methods in Hibernate?

Here’s my understanding of the methods. Mainly these are based on the API though as I don’t use all of these in practice.

saveOrUpdate
Calls either save or update depending on some checks. E.g. if no identifier exists, save is called. Otherwise update is called.

save
Persists an entity. Will assign an identifier if one doesn’t exist. If one does, it’s essentially doing an update. Returns the generated ID of the entity.

update
Attempts to persist the entity using an existing identifier. If no identifier exists, I believe an exception is thrown.

saveOrUpdateCopy
This is deprecated and should no longer be used. Instead there is…

merge
Now this is where my knowledge starts to falter. The important thing here is the difference between transient, detached and persistent entities. For more info on the object states, take a look here. With save & update, you are dealing with persistent objects. They are linked to a Session so Hibernate knows what has changed. But when you have a transient object, there is no session involved. In these cases you need to use merge for updates and persist for saving.

persist
As mentioned above, this is used on transient objects. It does not return the generated ID.

Leave a Comment