Suppose we loaded up a Parent
in one Session
, made some changes
in a UI action and wish to persist these changes in a new session by calling update()
.
The Parent
will contain a collection of childen and, since cascading update is enabled,
Hibernate needs to know which children are newly instantiated and which represent existing rows in the
database. Lets assume that both Parent
and Child
have genenerated
identifier properties of type Long
. Hibernate will use the identifier and
version/timestamp property value to determine which of the children are new. (See
Section 10.7, “Automatic state detection”.) In Hibernate3, it is no longer necessary to specify
an unsaved-value
explicitly.
The following code will update parent
and child
and insert
newChild
.
//parent and child were both loaded in a previous session parent.addChild(child); Child newChild = new Child(); parent.addChild(newChild); session.update(parent); session.flush();
Well, that's all very well for the case of a generated identifier, but what about assigned identifiers and composite identifiers? This is more difficult, since Hibernate can't use the identifier property to distinguish between a newly instantiated object (with an identifier assigned by the user) and an object loaded in a previous session. In this case, Hibernate will either use the timestamp or version property, or will actually query the second-level cache or, worst case, the database, to see if the row exists.