background preloader

Hibernate Mapping Cheat Sheet

Hibernate Mapping Cheat Sheet
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() // of Bar instances<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. Bidirectionality 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"> ... Now your Bars will know who their Foos are. No extra columns are generated for the bidirectionality. 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. Related: