甜咖啡

我的IT空间

hibernate 多对多映射配置详解

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");

}

posted on 2011-03-26 23:34 甜咖啡 阅读(3526) 评论(1)  编辑  收藏

评论

# re: hibernate 多对多映射配置详解[未登录] 2014-11-24 16:50 a


  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航:
 

导航

<2011年3月>
272812345
6789101112
13141516171819
20212223242526
272829303112
3456789

统计

常用链接

留言簿(1)

我参与的团队

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜