Hibernate / Hibernate interview questions II
Explain save, persist, saveOrUpdate and other object save methods in Hibernate.
Hibernate provides a handful of methods that store or update the object into the database. They are,
- save().
- update().
- saveOrUpdate().
- saveOrUpdateCopy().
- merge().
- and persist().
The purpose of these methods is as follows.
save method persists an entity. It assigns an identifier if entity doesn't exist in the database. If exists, save method performs an update. In both cases save method returns the generated ID of the entity.
Update method updates the existing object using identifier. If the identifier does not exist, it throws an exception.
saveOrUpdate method checks if the object is transient (i.e. it has no identifier) and if so it performs save that will make it persistent by generating an identifier and assigning it to session. If the object has an identifier already, it performs update().
saveOrUpdateCopy method is deprecated and no longer in use. Use merge method instead.
merge method is used to update the object to the database in any state of the session.
persist method makes a transient object persistent. However, it doesn't guarantee that the identifier value will be assigned to the persistent instance immediately, thats why the method does not return generated ID.
More Related questions...