文章目录
  1. 1. ER图
  2. 2. 实体类(JavaBean)
    1. 2.1. Department.java
    2. 2.2. Employee.java
  3. 3. 映射文件
    1. 3.1. Department.hbm.xml
    2. 3.2. Employee.hbm.xml
  4. 4. 测试类Many2One

多对一关联关系是Hibernate中很重要的一种关联关系。下面我们举例说明Hibernate中多对一的关联关系。

ER图

ER图
部门表有两个字段,id和部门名称name,id是主键;
员工表的主键是id,name指的是员工姓名,department_id是外键。
员工和部门就是多对一的关联关系。

实体类(JavaBean)

Department.java

1
2
3
4
5
public class Department {
private int id;
private String name;
//省略get、set方法
}

Employee.java

1
2
3
4
5
6
public class Employee {
private int id;
private String name;
private Department depart;
//省略get、set方法
}

映射文件

Department.hbm.xml

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="cn.zju.domain">
<class name="Department">
<id name="id">
<generator class="native" />
</id>
<property name="name"/>
</class>
</hibernate-mapping>

Employee.hbm.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="cn.zju.domain">
<class name="Employee" discriminator-value="0">
<id name="id">
<generator class="hilo"/>
</id>
<property name="name" unique="true"/>
<many-to-one name="depart" class="Department" column="depart_id"/>
</class>
</hibernate-mapping>

Hibernate提供many-to-one标签来实现多对一关联关系:

1
<many-to-one name="depart" class="Department" column="depart_id"/>

  1. name: 设定待映射的持久化类的属性的名字
  2. column: 设定和持久化类的属性对应的表的外键
  3. class:设定待映射的持久化类的属性的类型

    测试类Many2One

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    public void add() {
    Session s = null;
    Transaction tx = null;
    try {
    Department depart = new Department();
    depart.setName("depart name");
    Employee emp = new Employee();
    emp.setDepart(depart); //对象模型,建立两个对象的关联关系
    emp.setName("emp name");
    s = HibernateUtil.getSession();
    tx = s.beginTransaction();
    s.save(depart);
    s.save(emp);
    tx.commit();
    } finally {
    if (s != null)
    s.close();
    }
    }
文章目录
  1. 1. ER图
  2. 2. 实体类(JavaBean)
    1. 2.1. Department.java
    2. 2.2. Employee.java
  3. 3. 映射文件
    1. 3.1. Department.hbm.xml
    2. 3.2. Employee.hbm.xml
  4. 4. 测试类Many2One