Posted on 2009-06-20 19:11
胡娟 阅读(677)
评论(0) 编辑 收藏 所属分类:
JAVA
多对多关系关系映射
被关系维护端 teacher
package com.hujuan.bean;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
@Entity
public class Teacher {
private Integer id;
private String name;
private Set<Student> students = new HashSet<Student>();
public Teacher(){
}
public Teacher(String name){
this.name = name;
}
@Id @GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(nullable=false,length=10)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToMany(cascade=CascadeType.REFRESH,mappedBy="teachers")
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
@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;
final Teacher other = (Teacher) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
关系维护端student表
package com.hujuan.bean;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
@Entity
public class Student {
private Integer id;
private String name;
private Set<Teacher> teachers = new HashSet<Teacher>();
public Student(){
}
public Student(String name){
this.name = name;
}
@Id @GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(nullable=false,length=10)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//设置关联表
//inverseJoinColumns 被关系维护端在关联表中的外键
//joinColumns 关系维护端在关联表中的外键
@JoinTable(name="student_teacher",
inverseJoinColumns=@JoinColumn(name="teacher_id"),
joinColumns=@JoinColumn(name="student_id"))
@ManyToMany(cascade=CascadeType.REFRESH)
public Set<Teacher> getTeachers() {
return teachers;
}
public void setTeachers(Set<Teacher> teachers) {
this.teachers = teachers;
}
public void addTeacher(Teacher teacher){
this.teachers.add(teacher);
}
public void removeTeacher(Teacher teacher){
if(this.teachers.contains(teacher)){
this.teachers.remove(teacher);
}
}
}