Hibernate关联映射 --- 多对多实例分析(双向关联)

一  概念分析

1.多对多的经典实例(Teacher – Student)

二  代码分析

1.Teacher类

package com.hbsi.domain;

import java.util.Set;

//单向一对多  Teacher 一  对  多  Student

public class Teacher {

    private int id;

    private String name;

    private Set<Student> students;

    public Teacher() {

       super();

       // TODO Auto-generated constructor stub

    }

    public int getId() {

       return id;

    }

    public void setId(int id) {

       this.id = id;

    }

    public String getName() {

       return name;

    }

    public void setName(String name) {

       this.name = name;

    }

    public Set<Student> getStudents() {

       return students;

    }

    public void setStudents(Set<Student> students) {

       this.students = students;

    }

   

}

2.Stduent类

package com.hbsi.domain;

import java.util.Set;

public class Student {

    private int id;

    private String name;

    private Set<Teacher> teachers;

    public Student() {

       super();

       // TODO Auto-generated constructor stub

    }

    public int getId() {

       return id;

    }

    public void setId(int id) {

       this.id = id;

    }

    public String getName() {

       return name;

    }

    public void setName(String name) {

       this.name = name;

    }

    public Set<Teacher> getTeachers() {

       return teachers;

    }

    public void setTeachers(Set<Teacher> teachers) {

       this.teachers = teachers;

    }

}

3.Teacher的映射文件  Teacher.hbm.xml

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.hbsi.domain">

    <class name="Teacher" table="teacher">

       <id name="id" column="id">

           <generator class="native" />

       </id>

       <property name="name" column="name" />

       <!-- 集合属性的体现  多对多  table属性指定的是中间表的名字 -->

       <set name="students" table="teacher_student">

           <!--查中间表的外键 和老师的id的关联    老师的id-->

           <key column="teacher_id"/>

           <!-- 查学生的id和中间表的关系 -->

           <many-to-many class="Student" column="student_id"></many-to-many>

       </set>

    </class>

</hibernate-mapping>

4.Student的映射文件  Student.hbm.xml

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.hbsi.domain">

    <class name="Student" table="student">

       <id name="id" column="id">

           <generator class="native" />

        </id>

       <property name="name" column="name" />

       <set name="teachers" table="teacher_student">

           <key column="student_id"></key><!-- 查找这个学生被那个老师教 -->

           <many-to-many class="Teacher" column="teacher_id"></many-to-many>

       </set>

    </class>

</hibernate-mapping>

相关推荐