Entity Bean (5) : 多对多关系[转]

    技术2022-05-11  26

    学生和老师就是多对多的关系 。一个学生有多个老师,一个老师教多个学生。多对多映射采取中间表连接的映射策略,建立的中间表将分别引入两边的主键作为外键 EJB3 对于中间表的元数据提供了可配置的方式,用户可以自定义中间表的表名,列名。   下面是以学生和老师为例介绍多对多关系的实体 Bean 开发, 需要映射的数据库表:   Student table studentid ( 主键 ) Int(11) not null studentName varchar(32) not null   Teacher table teacherid ( 主键 ) Int(11) not null teacherName varchar(32) not null   中间表 teacher_student Student_ID Int(11) not null   st udent studentid 列的外键 Teacher_ID Int(11) not null   teacher teacherid 列的外键     public class Student implements Serializable {     private Integer studentid ;     private Set<Teacher> teachers = new HashSet<Teacher>();        。。。。     @ManyToMany (mappedBy = "students" )     public Set<Teacher> getTeachers() {        return teachers ;     } }   public class Teacher implements Serializable {     private Integer teacherid ;     private Set<Student> students = new HashSet<Student>();        。。。。     @ManyToMany (cascade = CascadeType. PERSIST , fetch = FetchType. LAZY )     @JoinTable ( name = "Teacher_Student" , joinColumns = { @JoinColumn (name = "Teacher_ID" , referencedColumnName = "teacherid" ) }, inverseJoinColumns = { @JoinColumn (name = "Student_ID" , referencedColumnName = "studentid" ) })     public Set<Student> getStudents() {        return students ;     }       public void addStudent(Student student) {        if (! this . students .contains(student)) {            this . students .add(student);        }     }   } Student class @ManyToMany 表示 Student 是多对多关系的一边, mappedBy 属性定义了 Student 为双向关系的维护端 (owning side)   Teacher class @ManyToMany 表示 Teacher 是多对多关系的一端。   @JoinTable 描述了多对多关系的数据表关系   Name 属性:指定中间表名称   joinColumns 属性: 定义中间表与 Teacher 表的外键关系 。上面的代码中,中间表 Teacher_Student Teacher_ID 列是 Teacher 表的主键列对应的外键列,   inverseJoinColumns 属性:定义了中间表与另外一端 (Student) 的外键关系      

    最新回复(0)