Reputation: 858
My code works well but shouldn't according to what I know about Hibernate.
I'm performing a save operation on a object as following:
IProfile profile = profileManager.getById(profileDtoModifyForm.getId());
profile.setName(profileDtoModifyForm.getName());
profile.setDescription(profileDtoModifyForm.getDescription());
profileManager.save(profile);
the profileManager.getById()
method uses org.Hibernate.Session.get()
method to get the object
the profileManager.save()
methode uses org.Hibernate.Session.save()
But I was expecting an error since the object is already stored in database and has an id.
instead, hibernate performs an update:
Hibernate: update profile set description=?, name=? where id=?
then I don't understand the difference between save and saveOrUpdate methods...
afters some researchs about that, I found a lot of description. One says hibernate performs an update if id exists, an other says it should throws an error...
ps: I use Spring, if it changes something...
Upvotes: 0
Views: 1610
Reputation: 124581
If you take a look at the javadoc of the Session.save
method you will see it talks about transient instances. This means non-hibernate managed entities. As you are doing a Session.getById
to retrieve an object it is an non-transient instance.
If you would use a transient instance it indeed would leed to an exception stating that an object with the given identifier already exists. However as this already is a managed instances this is detected and instead of a save an update is issued.
To test this just create a new instance of the profile you want to save, give it an id that already exists in the database and try to store it.
On another note because it already is a managed intance you don't even need the call to save
to have the changes persisted those will be automaticaly synchronized with the database.
The main difference between save
and saveOrUpdate
lies in the return type. When using save
a newly created id is returned saveOrUpdate
returns void
(the same for update
). But apart from that the internal code for storing the object in the database is the same regardless of the use of save
, update
or saveOrUpate
.
Upvotes: 1