Let’s say I have two classes, Parent and Child. These two are related via a uni-directional relationship.
<bag name="children" cascade="all">
<key column="parent_id" />
<one-to-many class="Child" />
</bag>
If I want to add a child element to the parent, as far as I know I need to load the parent, add a child to it, and save the parent:
Parent p = dao.getParent();
Child c = new Child();
p.getChildren().add(c);
dao.saveOrUpdate(p);
However, a problem arises when trying to mirror this change in the data model backing the GUI. As far as I can tell, there’s no way of finding the primary key that was assigned to c when it was persisted. This is causing a problem in the GUI, for if I add multiple rows to the model it’s impossible to distinguish them for later use.
Any ideas how I might be able to access the child’s primary key after it’s been persisted?
You can access autogenerated keys after the session is flushed, i.e. either after an explcit
session.flush()or after transaction commit.