24

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?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Hikari
  • 3,797
  • 12
  • 47
  • 77
  • Hi, did you check the Hibernate docs: http://www.hibernate.org/docs You don't mention which version you are using. Please use code blocks in the future. Thanks – Bizmarck Mar 05 '13 at 14:36

4 Answers4

24

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.

Pang
  • 9,564
  • 146
  • 81
  • 122
D3V
  • 1,543
  • 11
  • 21
  • 2
    save() method can do an SQL update if the id was assigned manually (and it exists in the database) – Kacper86 Aug 13 '13 at 14:04
6

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.

Pang
  • 9,564
  • 146
  • 81
  • 122
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

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
Community
  • 1
  • 1
Alex
  • 2,126
  • 3
  • 25
  • 47
1

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 .

javaaster
  • 41
  • 2