12

I am struggling to apprehend the slight differences between the hibernate methods

saveOrUpdate - update - save/persist.

I know there are some similar questions on the site:

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

Difference between save and saveOrUpdate method hibernate

but having read them, I did not notice an answer covering all the issues coming from using those methods in any case. I would to mention the example I have created to test: I have a table USER with the records:

id     |      company



1             Company1

2             Company2

I execute then the code:

 Session session = HibernateUtil.getSessionFactory().getCurrentSession();
 Transaction tx = session.beginTransaction();

 User user1 = (User) session.load(User.class, Integer.valueOf(1));
 user1.setCompany("Company3");
 User user2 = (User) session.load(User.class, Integer.valueOf(2));
 user2.setCompany("Company4");
 session.persist(user1);
 session.save(user2);

 tx.commit();

I see in the database:

id     |      company



 1             Company3

 2             Company4

I notice that save and persist in this case do the same task as saveOrUpdate or update.My question is therefore what is the diferrence between them and when are saveOrUpdate or update necessary. Am I right that with save or persist the associated objects are not updated even if using Cascade?

Community
  • 1
  • 1
arjacsoh
  • 8,932
  • 28
  • 106
  • 166
  • This is one of the [latest answers](https://stackoverflow.com/a/54907032/2788547) till date by Vlad Mihalcea the author himself. After digging through several old documentation threads, official doc, and many variants on Stack Overflow as well, this is one of the best-curated answers along with snippets. This [link](https://vladmihalcea.com/a-beginners-guide-to-jpa-hibernate-entity-state-transitions/) contains the entity lifecycle states as well just in case if you need it. – Aniket Jun 27 '21 at 17:22

3 Answers3

16

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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • You are right, the methods do nothing, since even without them the rows are updates in the database. – arjacsoh Sep 07 '14 at 10:33
  • 1
    You say "update() is used to attach a detached entity to the session." I had the impresssion this is the responsibity of "merge". If "update" is sufficient in that case then when does one need "merge"? – arjacsoh Sep 07 '14 at 10:35
  • 2
    merge does not attach its argument to the session. It gets the attached entity which has the same ID (and type) as its argument, then copies the state of the argument to the attached entity. merge() is a standard JPA method. saveOrUpdate() and update() are proprietary Hibernate methods. In general, you should use merge(). – JB Nizet Sep 07 '14 at 11:18
  • Since the data are update when the session flushes even with no "update", then when do we need update? I think a detached object should be attached with merge(), otherwise an Exception happens. – arjacsoh Sep 08 '14 at 13:05
  • 3
    The state of an **attached** entity is automatically saved to the database. `update()` is used to take a **detached** entity and attach it to the session. You don't *need* update() (it doesn't exist in JPA), but it can be useful, and is different from merge(). I repeat, merge() doesn't attach an object to the session. It copies the state of an detached entity to the attached entity which has the same ID. – JB Nizet Sep 08 '14 at 13:36
6

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

user2815238
  • 231
  • 3
  • 2
-1

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.

Dmytro Plekhotkin
  • 1,965
  • 2
  • 23
  • 47