码迷,mamicode.com
首页 > 移动开发 > 详细

Hibernate Many-to-Many Bidirectional mapping

时间:2015-10-26 12:07:21      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

1.Annotation

@Entity
public class Teacher {
    private String name;
    private int id;
    private Set<Student> students;

    @ManyToMany
    @JoinTable(name="t_s",
    //join column points to this.id;
        joinColumns={@JoinColumn(name="teacher_id")},
        //inverseJoinColumns points to id of student class
        inverseJoinColumns={@JoinColumn(name="stu_id")}
        )
    public Set<Student> getStudents() {
        return students;
    }
    public void setStudents(Set<Student> students) {
        this.students = students;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Id
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
}

@Entity
@Table(name="t_student")
public class Student {
    private int age;
    private int classID;
    private String name;
    private int id;
    private Set<Teacher> teachers;
    
    @ManyToMany(mappedBy="students")
    public Set<Teacher> getTeachers() {
        return teachers;
    }

    public void setTeachers(Set<Teacher> teachers) {
        this.teachers = teachers;
    }

    public int getClassID() {
        return classID;
    }
    
    public void setClassID(int classID) {
        this.classID = classID;
    }
    
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
    @Id
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
}

 

2.XML

Junction table‘s name and FK ,PK must match to each other!!

<hibernate-mapping package="com.hibernate.model">
<class name="Teacher" table="T_Teacher">
   <id name="id"></id>
    <property name="name"></property>
    <!-- table="xx" xx is name of junction table -->
    <set name="students" table="tea_stu">
      <key column="teacher_Id"></key>
      <many-to-many class="com.hibernate.model.Student" column="student_id"/>
    </set>
</class>

<class name="Student" table ="S_Student">
   <id name="id"></id>
    <property name="name"></property>
    <property name="age"></property>
    <property name="classID"></property>
    <set name="teachers" table="tea_stu">
      <key column="student_Id"></key>
      <many-to-many class="com.hibernate.model.Student" column="teacher_id"/>
    </set>
</class>

 

Hibernate Many-to-Many Bidirectional mapping

标签:

原文地址:http://www.cnblogs.com/fifi043/p/4910384.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!