文章目录
  1. 1. 概述
  2. 2. E-R图
    1. 2.1. 对象模型
  3. 3. 映射文件
    1. 3.1. Teacher.hbm.xml
    2. 3.2. Student.hbm.xml
  4. 4. 测试方法

概述

  • 多对多关联映射指的是两个对象之间是多对多的关系,比如teacher-student。
  • 由于在操作和性能方面都不太理想,所以多对多的映射使用较少,实际使用中最好转换成一对多的对象模型,Hibernate会为我们创建中间关联表,转换成两个一对多关联关系。

    E-R图

    E-R图

    对象模型

    1
    2
    3
    4
    5
    6
    7
    public class Student {
    private int id;
    private String name;
    private Set<Teacher> teachers;

    //省去get、set方法
    }
1
2
3
4
5
6
7
public class Teacher {
private int id;
private String name;
private Set<Student> students;

//省去get、set方法
}

映射文件

Teacher.hbm.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?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="Teacher">
<id name="id">
<generator class="native" />
</id>

<property name="name" />

<set name="students" table="teacher_student" inverse="true">
<key column="teacher_id"/>
<many-to-many class="Student" column="student_id"/>
</set>
</class>

</hibernate-mapping>
  • table:指定中间表
  • many-to-many:指定多对多的关联关系
  • column:执行set集合中的持久化类在中间表的外键列的名称
  • 注意要在其中一端加入inverse=”true”,否则会造成主键冲突

    Student.hbm.xml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    <?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="Student">
    <id name="id">
    <generator class="native" />
    </id>

    <property name="name" />

    <set name="teachers" table="teacher_student">
    <key column="student_id"/>
    <many-to-many class="Teacher" column="teacher_id"/>
    </set>
    </class>

    </hibernate-mapping>

测试方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public void add() {
Session s = null;
Transaction tx = null;
try {
Set<Teacher> ts = new HashSet<Teacher>();

Teacher t1 = new Teacher();
t1.setName("t1 name");
ts.add(t1);

Teacher t2 = new Teacher();
t2.setName("t2 name");
ts.add(t2);

Set<Student> ss = new HashSet<Student>();
Student s1 = new Student();
s1.setName("s1");
ss.add(s1);

Student s2 = new Student();
s2.setName("s2");
ss.add(s2);

t1.setStudents(ss);
t2.setStudents(ss);

s1.setTeachers(ts);
s2.setTeachers(ts);

s = HibernateUtil.getSession();
tx = s.beginTransaction();
s.save(t1);
s.save(t2);
s.save(s1);
s.save(s2);
tx.commit();
} finally {
if (s != null)
s.close();
}
}
文章目录
  1. 1. 概述
  2. 2. E-R图
    1. 2.1. 对象模型
  3. 3. 映射文件
    1. 3.1. Teacher.hbm.xml
    2. 3.2. Student.hbm.xml
  4. 4. 测试方法