Bidirectional one-to-many - II

2 September 2008

Do read the first part of this post. In this post, I will present a better way of specifying one to many relation.

The problem is that the link from p to c is not considered part of the state of the Child object and is therefore not created in the INSERT. The solution is to make the
link part of the Child mapping. This is done as follows:

<many-to-one name="parent" column="parent_id" not-null="true"/>

Now we have to tell the collection not to update the link since the Child entity is managing the state of the link. We use
the inverse attribute.

<set name="children" inverse="true">
<key column="parent_id"/>
<one-to-many class="Child"/>
</set>

The following code would be used to add a new Child

Parent p = (Parent) session.load(Parent.class, pid);
Child c = new Child();
c.setParent(p);
p.getChildren().add(c);
session.save(c);
session.flush();

continued …

del.icio.us:Bidirectional one-to-many - II  digg:Bidirectional one-to-many - II  spurl:Bidirectional one-to-many - II  wists:Bidirectional one-to-many - II  simpy:Bidirectional one-to-many - II  newsvine:Bidirectional one-to-many - II  blinklist:Bidirectional one-to-many - II  furl:Bidirectional one-to-many - II  reddit:Bidirectional one-to-many - II  fark:Bidirectional one-to-many - II  blogmarks:Bidirectional one-to-many - II  Y!:Bidirectional one-to-many - II  smarking:Bidirectional one-to-many - II  magnolia:Bidirectional one-to-many - II  segnalo:Bidirectional one-to-many - II  gifttagging:Bidirectional one-to-many - II

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: Bidirectional one-to-many - II

Leave a Reply