文章目录
  1. 1. 实体类(JavaBean)
    1. 1.1. Department.java
    2. 1.2. Employee.java
  2. 2. Department.hbm.xml
    1. 2.1. set
    2. 2.2. key
    3. 2.3. one-to-many

接续上一篇博客:如果我们从部门的角度去考虑部门和员工的关系,那么两者的关系就变为了一对多(一个部门对应多个员工)。我们继续用例子来说明一对多关联关系。

实体类(JavaBean)

Department.java

1
2
3
4
5
6
7
8
public class Department {
private int id;
private String name;

private Set<Employee> emps;

//省略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
13
14
15
16
<?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"/>
<set name="emps">
<key column="depart_id"></key>
<one-to-many class="Employee" />
</set>
</class>
</hibernate-mapping>

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

1
2
3
4
<set name="emps">
<key column="depart_id"></key>
<one-to-many class="Employee" />
</set>

set

name属性:指向待映射的持久化类

key

设定与所关联的持久化类对应的表的外键

  • column: 指定关联表的外键名

    one-to-many

    设定集合属性中所关联的持久化类
  • class: 指定关联的持久化类的类名
文章目录
  1. 1. 实体类(JavaBean)
    1. 1.1. Department.java
    2. 1.2. Employee.java
  2. 2. Department.hbm.xml
    1. 2.1. set
    2. 2.2. key
    3. 2.3. one-to-many