Wednesday, 20 April 2016

How to use Many to many mapping (collection) ?


A many-to-many reference is basically a collection.
Class A holds a reference to a set of class B instances (as in the one-to-many case), but B might have multiple A's.

Scenario

We have two classes, Foo and Bar which are related to each other as follows :
Set Foo.getBars()  // Set of Bar instances

Mapping
<class name="Foo" table = "foo">
  ...
  <set role="bars" table="foo_bar">
     <key column="foo_id"/>
     <many-to-many column = "bar_id" class = "Bar"/>
  </set>
</class>

This time we cannot have an extra column on Bar as that would dictate that each Bar has only one Foo.
So, instead we have an extra table, foo_bar, which holds the relationship between instances.


Bi-directionality

This relationship can be declared both ways, with Bar having getFoos(), by suitable code changes to Bar and the following schema change : 
<class name="Bar" table="bar">
  ...
  <set role="foos" table="foo_bar" readonly="true">
     <key column="bar_id"/>
     <many-to-many column="foo_id" class="Foo"/>
  </set>
</class>

Now your Bars will know who their Foos are.
  • No extra columns are generated for the bidirectionality.
  • Note that one end of the relationship must be declared "readonly".

If you want independent collections of Foos on Bars and Bars on Foos (i.e. membership one way doesn't imply the other), you need to declare Bar's table to be bar_foo.
That way an independent table will be used to keep track of the Foo set on Bar.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.