Hibernate saveOrUpdate vs update vs save/persist Hibernate saveOrUpdate vs update vs save/persist database database

Hibernate saveOrUpdate vs update vs save/persist


Both save() and persist() are used to insert a new entity in the database. You're calling them on entities that already exist in the database. So they do nothing.

The main difference between them is that save() is Hibernate-proprietary, whereas persist() is a standard JPA method. Additionally, save() is guaranteed to assign and return an ID for the entity, whereas persist() is not.

update() is used to attach a detached entity to the session.

saveOrUpdate() is used to either save or update an entity depending on the state (new or detached) of the entity.

Note that you don't need to call any method of the session to modify an attached entity: doing

User user1 = (User) session.load(User.class, Integer.valueOf(1));user1.setCompany("Company3");

is sufficient to have the company of the user 1 updated in the database. Hibernate detects the changes made on attached entities, and saves them in the database automatically.


saveSave method stores an object into the database. That means it insert an entry if the identifier doesn’t exist, else it will throw error. If the primary key already present in the table, it cannot be inserted.

updateUpdate method in the hibernate is used for updating the object using identifier. If the identifier is missing or doesn’t exist, it will throw exception.

saveOrUpdateThis method calls save() or update() based on the operation. If the identifier exists, it will call update method else the save method will be called. saveOrUpdate() method does the following:If the object is already persistent in the current session, it do nothingIf another object associated with the session has the same identifier, throw an exception to the callerIf the object has no identifier property, save() the objectIf the object’s identifier has the value assigned to a newly instantiated object, save() the object- See more at: http://www.javabeat.net/difference-between-hibernates-saveupdate-and-saveorupdate-methods/#sthash.ZwqNlWXH.dpuf


saveOrUpdate - inserts a row if it does not exist in a database or update it if it does exist.

save - always try to insert a row into a database.

update - always try to update a row in a database.Example of using saveOrUpdate.

Assume that you developed the program that gets the information about user visits for current day from Google Analytics and saves it into your database.

If there are no information about the day in your database, method saveOrUpdate will insert the data, otherwise it will update existing data.