Hibernate saveOrUpdate vs update vs save/persist

三世轮回 提交于 2019-12-03 06:45:28

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.

save Save 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.

update Update 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.

saveOrUpdate This 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 nothing If another object associated with the session has the same identifier, throw an exception to the caller If the object has no identifier property, save() the object If 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!