Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between save and saveOrUpdate method hibernate [duplicate]

Tags:

Normally I had read about save() method generates new identifier for object and only fire INSERT and save it, it does not update it, while saveOrUpdate() method may INSERT or UPDATE record.

But as per my experience, Here I can explains better by sample code,

Suppose there is Class A, and I find record from Table A by

A a = getHibernateTemplate.findById(7); 

So now I get a persistent object,

And now I am trying to save record with save method by simply modifying some of fields,

Now I am firing,

getHibernateTemplate.save(a); 

So it just update existing record, but as per my knowledge it should create new record.

I may be wrong about certian things, can someone clear about this?

like image 849
commit Avatar asked Jul 12 '13 10:07

commit


People also ask

What is the difference between Save () and persist () method in hibernate?

Difference between save and persist method in Hibernate First difference between save and persist is there 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.

What is difference between Merge and saveOrUpdate in hibernate?

Once save/update is done, the object DOES NOT reflect the change. The returned object reflects the changes, and it is attached to hibernate session. MERGE method offers greater flexibility when it comes to saving data objects, since you need not worry about attaching object to Session.

What is Save () and update () method in hibernate?

save() method runs the insert query, update() method runs the update query and saveOrUpdate() method first run the select query and then run insert or update query depending on data exist in database or not against given identifier. save() method also returns the generated identifier.

What is Save method 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.


1 Answers

save

Save method stores an object into the database. It will Persist the given transient instance, first assigning a generated identifier. It returns the id of the entity created.

Whereas,

SaveOrUpdate()

Calls either save() or update() on the basis of identifier exists or not. e.g if identifier exists, update() will be called or else save() will be called.

There are many more like persist(), merge(), saveOrUpdateCopy(). Almost all are same giving slight different functionality and usability.

For more, you can read this. What are the differences between the different saving methods in Hibernate?

like image 50
PVR Avatar answered Sep 23 '22 10:09

PVR