12hibernate hibernate的关系映射之ManyToMany(重点)

来源:互联网 发布:mac电脑声音很大 编辑:程序博客网 时间:2024/05/18 01:26
1.多对多单向关联(老师知道教了哪些学生,学生并不知道被哪些老师教)a.数据库:中间表b.annotation:@Entitypublic class Teacher{private int id;private String name;@ManyToMany@JoinTable(name="t_s",//可修改默认中间表的名称JoinColumns{@JoinColumn(name="teacher_id")},//定义当前类在中间表中的列名,并参考当前类的idinverseJoinColumns={@JoinColumn(name="student_id")}//定义对方类在中间表中的外键的名称,参考对方类的id)private Set<Student> students = new HashSet<Student>();}@Entitypublic class Student{private int id;private String name;}//默认生成中间表Teacher_Student//默认中间表包含Teacher_id和students_id两个字段c.xml:<class name="com.hibernate.Teacher"><id name="id"><generator class="native"></generator></id><property name="name"></property><set name="students" table="t_s"><key column="teacher_id"></key>//相当于JoinColumn,指向自己这张表的外键名称<many-to-many class="com.hibernate.Student" column="student_id"></many-to-many>//column="student_id"指向对方那张表的外键名称</set></class><class name="com.hibernate.Student"><id name="id"><generator class="native"></generator></id><property name="name"></property></class>2.多对多双向关联(比较少用)a.annotation:@Entitypublic class Teacher{private int id;private String name;@ManyToMany@JoinTable(name="t_s",JoinColumns{@JoinColumn(name="teacher_id")},inverseJoinColumns={@JoinColumn(name="student_id")})private Set<Student> students = new HashSet<Student>();}@Entitypublic class Student{private int id;private String name;@ManyToMany(mappedBy="students")private Set<Teacher> teachers = new HashSet<Teacher>();}//数据库表没有变化b.xml:Teacher类的xml不变<class name="com.hibernate.Student"><id name="id"><generator class="native"></generator></id><property name="name"></property><set name="teachers" table="t_s"><key column="student_id"></key><many-to-many class="com.hibernate.Teacher" column="teacher_id"></many-to-many></set></class>

0 0