JPA关联关系多对多2009-01-14 15:44学生Student,与老师Teacher是多对多的关系。需要一张中间表,Teacher_Student,里面有两个字段teacherid,studentid共同组成主键. Teacher_Student不用生成一个实体类. 在Student类里面:./ .... @ManyToMany(mappedBy = "students") private List teachers; ....... students是Teacher类里面的List students 在Teacher类里面: ....... @ManyToMany(cascade = CascadeType.PERSIST) @JoinTable(name = "Teacher_Student", joinColumns = {@JoinColumn(name = "teacherid")}, inverseJoinColumns = {@JoinColumn(name = "studentid")} ) private List students; ..... 首先声明ManyToMany,cascade一定要用PERSIST,当我们添加老师数据的时候就会在Teacher_Student里面自动添加对应的数据,而当我们删除老师数据的时候就会自动在Teacher_Student表里面自动删除相应的记录. 接着是用到了JoinTable,name属性为中间表的名字。 设置joinColumns属性,指定关系维护端(owner side),即Teacher类本身.使用JoinColumn,name指向数据库字段,referencedColumnName指向实体类里面的属 性,当数据库字段与实体类的名字相同的时候可以省略. 设置inverseJoinColumns,指定关系被维护端(inverse side),即映射到Student类,设置方法与joinColumns一样.
多对多映射采取中间表连接的映射策略,建立的中间表将分别引入两边的主键作为外键。
EJB3对于中间表的元数据提供了可配置的方式,用户可以自定义中间表的表名,列名。
假设Teacher 和 Student是多对多的关系,具体元数据声明如下:
pubic class Teacher{ @ManyToMany(targetEntity = Student.class, cascade = CascadeType.PERSIST) @JoinTable(table = @Table(name = "M2M_TEACHER_STUDENT"), joinColumns = @JoinColumn(name = "TEACHER_ID", referencedColumnName = "ID"), inverseJoinColumns = @JoinColumn(name = "STUDENT_ID", referencedColumnName = "ID")) public List<Student> getStudents() {return students;} }public class Student{ @ManyToMany(targetEntity = Teacher.class, mappedBy = "students") public List<Teacher> getTeachers() { return teachers; }} 代码中元数据的说明:
元数据描述:
@ManyToMany(targetEntity = Student.class, cascade = CascadeType.PERSIST)
targetEntity = Student.class表明关系另一端的实体类型。cascade声明级联操作。
@JoinTable(table = @Table(name = "M2M_TEACHER_STUDENT"),
joinColumns = @JoinColumn(name = "TEACHER_ID", referencedColumnName = "ID"),
inverseJoinColumns = @JoinColumn(name = "STUDENT_ID", referencedColumnName = "ID"))
JoinTable配置中间表信息,它由3个部分组成:
1) table = @Table(name = "M2M_TEACHER_STUDENT") ,声明中间表的名字
2) joinColumns ,定义中间表与关系维护端的外键关系。
3) inverseJoinColumns,定义中间表与inverse端的外键关系.
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/Senton/archive/2007/03/15/1529969.aspx