多对多关系

 

//省略了set方法

/**
 * 关系维护端
 */
@Entity
@Table(name="student_many")
public class Student {
 private Integer id;
 private String name;
 private Set<Teacher> teacher = new HashSet<Teacher>();
 
 public Student(){}
 
 public Student(String name) {
  super();
  this.name = name;
 }

//inverseJoinColumns 表示关联对方表主键,映射到中间表的字段为teacher_id
 @ManyToMany(cascade=CascadeType.REFRESH)
 @JoinTable(name="student_teacher",inverseJoinColumns=@JoinColumn(
   name="teacher_id"),joinColumns=@JoinColumn(name="student_id"))
 public Set<Teacher> getTeacher() {
  return teacher;
 }

 @Id @GeneratedValue
 public Integer getId() {
  return id;
 }
 @Column(length=20,nullable=false)
 public String getName() {
  return name;
 }

 public void addTeacher(Teacher teacher){
  this.teacher.add(teacher);
 }
 public void removeTeacher(Teacher teacher){
  if(this.teacher .contains(teacher)){
   this.teacher.remove(teacher);
  }
 }

}

 

 


@Entity
@Table(name="teacher_many")
public class Teacher {
 private Integer id;
 private String name;
 private Set<Student> student = new HashSet<Student>();
 
 public Teacher(){}
 
 public Teacher(String name) {
  super();
  this.name = name;
 }
 @ManyToMany(cascade=CascadeType.REFRESH,mappedBy="teacher")
 public Set<Student> getStudent() {
  return student;
 }
 public void setStudent(Set<Student> student) {
  this.student = student;
 }
 @Id @GeneratedValue
 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 @Column(length=20,nullable=false)
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }

 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + ((id == null) ? 0 : id.hashCode());
  return result;
 }

 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Teacher other = (Teacher) obj;
  if (id == null) {
   if (other.id != null)
    return false;
  } else if (!id.equals(other.id))
   return false;
  return true;
 }
 

}

 

posted @ 2013-04-15 20:28  若 ♂ 只如初见  阅读(163)  评论(0编辑  收藏  举报