Student与Teacher关系多对多(只建了2个实体类)
1 public class Student { 2 private int id; 3 private String name; 4 private Set<Teacher> teachers = new HashSet<Teacher>(); 5 }
1 public class Teacher { 2 private int id; 3 private String name; 4 private Set<Student> students = new HashSet<Student>(); 5 }
多对多
1 <hibernate-mapping package="entity"> 2 <class name="Student"> 3 <id name="id"> 4 <generator class="native"/> 5 </id> 6 <property name="name"/> 7 <!-- 8 <set>标签的table属性: 配置关系表的名称 9 <key>标签的column属性: 当前实体对应数据库表的外键字段名 10 <many-to-many>标签表示多对多关系,属性: 11 class属性: 表示对方的类名 12 column属性: 表示对方的表在关系表中的外键字段名 13 --> 14 <set name="teachers" table="StudentTeacher" cascade="save-update"> 15 <key column="studentId"/> 16 <many-to-many class="Teacher" column="teacherId" /> 17 </set> 18 </class> 19 </hibernate-mapping>
1 <hibernate-mapping package="entity"> 2 <class name="Teacher"> 3 <id name="id"> 4 <generator class="native"/> 5 </id> 6 <property name="name"/> 14 <set name="students" table="StudentTeacher" cascade="save-update"> 15 <key column="teacherId"/> 16 <many-to-many class="Student" column="studentId" /> 17 </set> 18 </class> 19 </hibernate-mapping>