Does anyone know how Hibernate knows whether to INSERT or to UPDATE a value in the database when session.saveOrUpdate() is called?
So far, I have only determined that it is not dependent on the information in the cache, and that the existence of the entity in the database is determined by the primary key.
When you use
.saveOrUpdate()Hibernate will check if the object is transient (it has no identifier property) and if so it will make it persistent by generating it the identifier and assigning it to session. If the object has an identifier already it will perform.update().From the documentation:
saveOrUpdate() does the following:
in this session, do nothing
session has the same identifier,
throw an exception
property, save() it
value assigned to a newly
instantiated object, save() it
“version” or “timestamp”, and the
version property value is the same
value assigned to a newly
instantiated object, save() it
otherwise update() the object