1-简单联合 1对1
1.1-定义:一个类含有单个的另一个类实例的引用。他们通过共有的主键(pk)结合。
1.2-Bar Foo.getBar() // returns corresponding Bar instance
1.3-Hibernate 映射:
<class name="Foo" table="foo" ... <one-to-one name="bar" class="Bar"/> </class> |
1.4-数据库表结构:
Foo |
id |
Bar |
id |
1.5-Foo 和 Bar 必须共享相同的PK值 作为1对1关系的一部分。
如果你创建了有共享PK的 Foo 和 Bar的实例, 那么读取一个Foo类的同时也会读取一个Bar类的实例子。
1.6-反方向:这个关系可以转为反方向, Bar类含有getFoo()方法, 通过简单地增加一个简单的映射并且增加一个Foo 属性给Bar类.
2-简单引用 多对1
2.1-定义:多对1引用和简单的引用很相似. 它和简单的1对1关系的情况很相似除了没有对共享PK的要求,而是用到了外键(FK )。
2.2-Bar Foo.getBar() // returns corresponding Bar instance
2.3-Hibernate 映射:
<class name="Foo" table="foo"> ... <many-to-one name="bar" class="Bar" column="bar_id"/> </class> |
2.4-数据库表结构:
Foo | |
id | bar_id |
Bar |
id |
2.5-现在我们在Foo的表里增加了额外的字段, 这个字段保存到Bar表的外键. Foo和Bar现在可以拥有不同的主键PK,而他们的关系却可以依然保持。
2.6-反方向:这个关系可被声明为2种方向, 另外一种就是 Bar 类含有 getFoo()方法, 通过增加一个相似的mapping 和属性到Bar. 这会导致Bar表增加额外的字段 foo_id。
3-基本集合 1对多
3.1-定义:
1对多引用是基于集合。主类A持有对类B集合的引用。
3.2-Set Foo.getBars() // returns a collection of Bar instances
3.3-Hibernate 映射:
<class name="Foo" table="foo"> ... <set role="bars" table="bar"> <key column="foo_id"/> <one-to-many class="Bar"/> </set> </class> |
3.4-数据库表结构:
Foo |
id |
Bar | |
id | foo_id |
3.5-现在我们在Bar表里面创建额外的字段保存到Foo表的外键. 这允许Foo被赋于Bar的集合基于字段foo_id的值。
3.6-反方向:
This relationship can be declared both ways, with Bar having getFoo(), by suitable code changes to Bar and the following schema change:
<class name="Bar" table="bar"> ... <many-to-one name="foo" class="Foo" column="foo_id"/> </class> |
现在Bar知道它包含的Foo都是哪些啦,而且不需要添加额外的字段来实现这种方向。
4-集合 多对多
4.1-定义:多对多关系也是一种基于集合的. A持有对B类集合的引用,B也持有对A类集合的引用。
4.2-Set Foo.getBars() // returns a collection of Bar instances
4.3-Hibernate 映射:
4.4-数据库表结构:
Foo |
id |
Bar |
id |
Foo_Bar | |
foo_id | bar_id |
这次我门不能在Bar表中添加额外的字段,那样就会表明每个Bar只有一个Foo。所以我们新建了一个表Foo_Bar,用来储存实例的关系。
4.5-反方向:通过Bar 类包含getFoos()方法, 更改Bar 的代码和下面的映射:
<class name="Bar" table="bar">
...
<set role="foos" table="foo_bar">
<key column="bar_id"/>
<many-to-many column="foo_id" class="Foo"/>
</set>
</class>
现在Bar知道它包含的Foo都是哪些啦,而且不需要添加额外的字段来实现这种方向。如果你希望Foo的Bars或者Bar的Foos互相独立 (i.e. membership one way doesn't imply the other), 你需要声明Bar的表为 bar_foo. 一个专门的表将用来保持Bar-->Foos的信息。
<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> |