hibernate annotation多对多中间表添加其他字段的第三种方法
本示例主要以学生(T_Student)和课程(T_Course)之间的多对多关系,中间表Score(分数),学生表和课程表是多对多关系,另外为他们的关系添加额外的字段---分数:
T_Student类如下:
package server.com.upc.test;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
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.MapKey;
@Entity
public class T_Student {
private int id;
private String name;
private Map<String,T_Crouse> course=new HashMap<String,T_Crouse>();
/*
* 或者
* private Set<T_Crouse> course=new HashSet<T_Crouse>();
*
* */
@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="score",
joinColumns=@JoinColumn(name="student_id"),
inverseJoinColumns=@JoinColumn(name="course_id")
)
*
*/
@ManyToMany
@MapKey(name="id")
@JoinTable(
name="score",
joinColumns=@JoinColumn(name="student_id"),
inverseJoinColumns=@JoinColumn(name="course_id")
)
public Map<String, T_Crouse> getCourse() {
return course;
}
public void setCourse(Map<String, T_Crouse> course) {
this.course = course;
}
}
T_course类:
package server.com.upc.test;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class T_Crouse {
private int id;
private String name;
@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;
}
}
中间表Score也写成实体类:
package server.com.upc.test;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity
@Table(name="score")
public class T_Score {
private int id;
private int scrores;
private T_Student student;
private T_Crouse course;
@Id
@GeneratedValue
public int getId() {
return id;
}
public int getScrores() {
return scrores;
}
public void setScrores(int scrores) {
this.scrores = scrores;
}
public void setId(int id) {
this.id = id;
}
@ManyToOne
@JoinColumn(name="student_id")
public T_Student getStudent() {
return student;
}
public void setStudent(T_Student student) {
this.student = student;
}
@ManyToOne
@JoinColumn(name="course_id")
public T_Crouse getCourse() {
return course;
}
public void setCourse(T_Crouse course) {
this.course = course;
}
}
注意的是中间表中的导航关系manytomany @JoinColumn(name="course_id");@JoinColumn(name="course_id")中声明的course_id,student_id和T_student表中声明的要一致,不然会产生其他的字段--再就是中间表的@Table(name="score")score名字和T_Student中的 @JoinTable(
name="score",要一样!!!
建立好之后就会生成中间表含有字段id,student_id,course_id,和score四个字段(然后hibernate生成的主键是(student_id,coure_id))虽然你在T_Score表中声明了自己的id。。。。这是值得注意的地方!