Hikari
Hikari

Reputation: 3947

What exactly does org.hibernate.Session.save() do?

I know that Session.save() persists the transient object. And I see that it also has saveOrUpdate(), and also persist().

I suppose then that save() is equivalent to SQL INCLUDE, is it?

If I have an object that already exists on DB and I save() it, will another row be included, will its fields be updated, or will it just be ignored and nothing happen?

Upvotes: 24

Views: 48691

Answers (4)

Suresh Atta
Suresh Atta

Reputation: 121998

From this answer:

save Persists an entity. Will assign an identifier if one doesn't exist. If one does, it's essentially doing an update. Returns the generated ID of the entity.

I suggest you read the linked answer for further info.

Upvotes: 6

D3V
D3V

Reputation: 1593

Difference between save and saveOrUpdate

Main difference between save and saveOrUpdate method is that save generates a new identifier and INSERT record into database while saveOrUpdate can either INSERT or UPDATE based upon existence of record. So save will proceed without performing existence check, on the other hand saveOrUpdate will check for existence, if record exists it will be updated else a new record will be inserted.

Basic differences between persist and save

  1. First difference between save and persist is their return type. Similar to save method, persist also INSERT records into database but return type of persist is void while return type of save is Serializable object.

  2. Another difference between persist and save is that both methods make a transient instance persistent. However, persist method doesn't guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time.

Upvotes: 24

javaaster
javaaster

Reputation: 41

save() method insert the record into database . but saveorupdate() method check the pk if pk is found then it's update the data else insert the data into database .

Upvotes: 1

Alex
Alex

Reputation: 2146

As far as I know it's happening like this:

  1. save() is just saving your entity
  2. persist() is modifying your instance as managed entity. this means that if you do an operation on it and your transaction is still open then it will be automatically saved when you call flush() (if I am not mistaken)
  3. merge() there is also this one which is like persist() but it's returning a new instance and not modifying your old instance....
  4. saveOrUpdate() you can see here

Upvotes: 2

Related Questions