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?
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.
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.
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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With