1.

Differentiate between save() and saveOrUpdate() methods in hibernate session.

Answer»

Both the methods save records to the table in the database in case there are no records with the primary key in the table. However, the main differences between these two are listed below:

save()saveOrUpdate()
save() generates a new IDENTIFIER and INSERT RECORD into a databaseSession.saveOrUpdate() can either INSERT or UPDATE based upon existence of a record.
The insertion fails if the primary key ALREADY exists in the table.In case the primary key already exists, then the record is updated.
The return type is Serializable which is the newly generated identifier ID value as a Serializable object.The return type of the saveOrUpdate() method is void.
This method is used to bring only a transient object to a persistent state.This method can bring both transient (new) and detached (existing) objects into a persistent state. It is often used to re-attach a detached object into a Session

Clearly, saveOrUpdate() is more flexible in terms of use but it involves extra processing to find out whether a record already exists in the table or not.



Discussion

No Comment Found