您的位置:首页 > 其它

1.22 多对多(双向)

2015-12-20 20:44 225 查看
       老师与学生的关系为多对多,其中通过老师找到学生(为单向),而通过老师找到学生,或者学生找到老师为双向。

         双向的多对多比较少用。

一、annotation实现方式

       1.teacher类

@Entity

public class Teacher {
private int id;
private String name;
private Set<Student> students = new HashSet<Student>();
@Id
@GeneratedValue
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;
}
@ManyToMany
@JoinTable(name="t_s",
joinColumns={@JoinColumn(name="teacher_id")},
inverseJoinColumns={@JoinColumn(name="student_id")}
)
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}

}

2.student类

@Entity

public class Student {
private int id;
private String name;
private Set<Teacher> teachers = new HashSet<Teacher>();
@ManyToMany(mappedBy="students")
public Set<Teacher> getTeachers() {
return teachers;
}
public void setTeachers(Set<Teacher> teachers) {
this.teachers = teachers;
}
@Id
@GeneratedValue
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;
}

}

3.在hibernate.cfg.xml中配置相应的类。

二、xml实现方式

1.student.hbm.xml

<hibernate-mapping>
<class name="com.bjsxt.hibernate.Student">
<id name="id">
<generator class="native"></generator>
</id>

<property name="name"></property>
<set name="teachers" table="t_s">
<key column="student_id"></key>
<many-to-many class="com.bjsxt.hibernate.Teacher" column="teacher_id"/>
</set>

    </class>

</hibernate-mapping>

2、teacher的配置

<hibernate-mapping>
<class name="com.bjsxt.hibernate.Teacher">
<id name="id">
<generator class="native"></generator>
</id>

<property name="name"></property>
<set name="students" table="t_s">
<key column="teacher_id"></key>
<many-to-many class="com.bjsxt.hibernate.Student" column="student_id"/>
</set>

    </class>

</hibernate-mapping>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: