---
title: "Hibernate中的关联关系 "
author: "ivorytower"
date: "2008-04-16T15:16:34Z"
tags: []
categories: ["企业架构"]
slug: "hibernate"
draft: false
lastmod: "2008-04-16T15:16:34Z"
id: 183398
url: "https://ivorytower.iteye.com/blog/183398"
---

初学 hibernate  时是被 hibernate 中的复杂的关系搞得晕头转向。 一对多 ，多对一，多对多。单向，双向等等 

问题就出在，找不到参照方物，其实只要找准参照物，各种关系自然迎刃而解。在关系型数据库中 实际上通过主外键只支持多对一，或是一对一单向关联。

1，多对一单向关联 ： 以客户表 (customer) 和定单表（orders ）为例。一个客户可以发出多个定单，而一个定单只可以属于一个客户。从 orders 到customer 就是 多对一的关系。这就意味着， orders 中应该有一个 Customer类型的属性。

![](http://p.blog.csdn.net/images/p_blog_csdn_net/caoyinghui1986/Noname.jpg)
因为在关系型数据库中只有主外键参照关系，而且总是有 many 方参照 one 方，这样可以消除数据冗余。

 所以一般是一主键表为参照物。

在hbm.xml 配置时 

```xml
   <many-to-one 

                                      name="customer"

                                     column="id"

                                     class="hib.Customer"

                                      not-null="true"

                           >

```


name: 指定了持久化类的属性名 （Order类的 customer属性）

column : 指定属性对应的外键 （order表的 customer_id）

class :指定了持久化类的类型。

2，一对多单向关联 ：从 customer 到 order 是一对多。意味着每个 customer对象会引用一组order对象。 

                        所以在 customer中应该定义一个集合类型的属性，来关联所引用的 order对象。
![](http://p.blog.csdn.net/images/p_blog_csdn_net/caoyinghui1986/Noname2.jpg)
hbm.xml 文件配置时

```xml
   
                        <set  

                             name="orders"

                             cascade="save-update"

                          >

                                    <key column ="custome_id" />  

                                   <one-to-many  class="hib.Order"/>

                         </set>

```

name ：指定持久化类的属性名 （Customer类的 orders 属性）

<set> : 表明 Customer 类的属性类型为 java.util.Set  类型。

<one-to-many> :表明 orders 集合中存放的是一组 Order对象。

如果一个类关联另一个类，而另一个类不关联这个类。我们就认为这种关联是单向关联

两个类相互包含另一个类的属性时 我们就人认为着种关联是双向关联。

3，一对多双向关联：综合上面两种。

![](http://p.blog.csdn.net/images/p_blog_csdn_net/caoyinghui1986/Noname3.jpg)