package cn.edu.hpu.many2many; import java.util.HashSet; import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table(name="m_student") 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; } }
package cn.edu.hpu.many2many; import java.util.HashSet; import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; import cn.edu.hpu.many2many.Student; @Entity @Table(name="m_teacher") public class Teacher { private int id; private String name; private Set<Student> students=new HashSet<Student>(); //选择set的原因是因为,set互相之间不会有重复的 //跟数据库模型比较匹配 @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")},//指明的是当前这个实体类的表的名字(加s防止联合主键) inverseJoinColumns={@JoinColumn(name="student_id")}//逆转的、对方的的表名(所对应的另一张表) ) public Set<Student> getStudents() { return students; } public void setStudents(Set<Student> students) { this.students = students; } }
<mapping class="cn.edu.hpu.many2many.Student"/> <mapping class="cn.edu.hpu.many2many.Teacher"/>
转载请注明出处:http://blog.csdn.net/acmman