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?

1
  • Hi, did you check the Hibernate docs: hibernate.org/docs You don't mention which version you are using. Please use code blocks in the future. Thanks
    – Bizmarck
    Mar 5, 2013 at 14:36

4 Answers 4

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.

1
  • 2
    save() method can do an SQL update if the id was assigned manually (and it exists in the database)
    – Kacper86
    Aug 13, 2013 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.

0
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
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 .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.