Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I modify a Hibernate entity, after doing a save, when I commit would the changes be saved to the database

If in Hibernate, I do the following steps:

  1. Open a session.
  2. Create a new hibernate POJO object (that is to be saved), and fill in the values.
  3. Now I do session.save().
  4. Now I change the POJO object - say it is an employee object and I do emp.setName("Other Name") i.e change the name of the employee in the object.
  5. Now I do a transaction commit.

My question is what would be saved to the database - the name before I did session.save() or the name after the change i.e. "Other Name"?

like image 974
coderPrimary Avatar asked Jun 20 '15 15:06

coderPrimary


People also ask

What is difference between save and saveOrUpdate in Hibernate?

Difference between save and saveOrUpdate in Hibernate The main difference between save and saveOrUpdate method is that save() generates a new identifier and INSERT record into the database while saveOrUpdate can either INSERT or UPDATE based upon the existence of a record.

How save or update works in Hibernate?

The save() method INSERTs an object in the database. It will persist the given transient instance, first assigning a generated identifier. It returns the id of the entity created. The saveOrUpdate() calls either save() or update() on the basis of identifier exists or not.

What is difference between save and persist in Hibernate?

The save method proves to be of less use in a long-running conversation that has extended a given Session context. As the persist method is called outside the transaction boundaries, it is utilized in long-running conversations that offer an extended Session context. Save() method gets support only through Hibernate.

Does Hibernate update if no changes?

No. Strictly speaking, Hibernate does not send an SQL update on update . update simply updates the object in the current session. Hibernate executes queries when the session is flushed.


2 Answers

The moment you saved the entity, it becomes managed and all further changes are propagated to the database during Session.flush.

When you saved the entity, you only triggered an EntityInsertAction to be queued. After you changed the entity, the current entity state was changed so during a flush, Hibernate will simply insert the latest entity state, so the database will contain the "Other Name".

In fact, calling a method like save for a managed entity (which triggers an entity merge) is actually going to affect performance.

like image 172
Vlad Mihalcea Avatar answered Sep 20 '22 15:09

Vlad Mihalcea


While working with managed entity, when you don't call save, it will be saved automatically.

like image 29
Adam Tychoniewicz Avatar answered Sep 18 '22 15:09

Adam Tychoniewicz