Red Hat Training

A Red Hat training course is available for Red Hat JBoss Web Server

21.5. Cascades and Unsaved-value

Suppose we loaded up a Parent in one Session, made some changes in a UI action and wanted to persist these changes in a new session by calling update(). The Parent will contain a collection of children and, since the cascading update is enabled, Hibernate needs to know which children are newly instantiated and which represent existing rows in the database. We will also assume that both Parent and Child have generated identifier properties of type Long. Hibernate will use the identifier and version/timestamp property value to determine which of the children are new. (Refer to the "Automatic State Detection: section for further information) 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
Child newChild = new Child();
This may be suitable for the case of a generated identifier, but for assigned identifiers and composite identifiers it is more difficult, since Hibernate cannot 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.