hibernate 多对多映射配置详解
2008-12-12 17:04
表关系 如图:
Teacher.java文件:
private int id;
private String name;
private Set teachers;
Student.java文件:
private int id;
private String name;
private Set students;
Teacher.hbm.xml 配置文件内容:
<hibernate-mapping>
<class name="com.bean.Teacher" table="teacher">
<id name="id" type="int">
<column name="id"></column>
<generator class="native"></generator>
</id>
<property name="name" type="java.lang.String" column="name"></property>
<set name="students" table="student_teacher" cascade="all">
<key column="teacher_id"></key>
<many-to-many class="com.bean.Student" column="student_id"></many-to-many>
</set>
</class>
</hibernate-mapping>
Student.hbm.xml 配置文件内容:
<hibernate-mapping>
<class name="com.bean.Student" table="student">
<id name="id" type="int">
<column name="id"></column>
<generator class="native"></generator>
</id>
<property name="name" type="java.lang.String" column="name"></property>
<set name="teachers" table="student_teacher" cascade="all">
<key column="student_id"></key>
<many-to-many class="com.bean.Teacher" column="teacher_id"></many-to-many>
</set>
</class>
</hibernate-mapping>
test测试类部分代码:
List list = session.createQuery("from Teacher").list();
for(int i=0; i<list.size(); i++){
Teacher teacher = (Teacher)list.get(i);
System.out.println("Teacher_name: "+teacher.getName());
Iterator it = teacher.getStudents().iterator();
while(it.hasNext()){
Student student =(Student) it.next();
System.out.println("student_name: "+student.getName());
}
System.out.print("---------------------------\n");
}