随笔 - 23  文章 - 15  trackbacks - 0
<2007年8月>
2930311234
567891011
12131415161718
19202122232425
2627282930311
2345678



留言簿(3)

随笔分类(19)

搜索

  •  

最新随笔

最新评论

阅读排行榜

评论排行榜

hibernate在解决数据持久化方面的确是很强大,在此给出数据库表中的MANY-TO-MANY在hibernate中是如何映射的.

其实呢多对多的关系映射,是在一对多的基础上进行的。
如果现在数据库中有两张表(经典的多对多:student-teacher)
student: studentid(primary key ),studentname
teacher: teacherid(primary key ),teachername
存放其关系的表:stu_tea_relation: studentid,teacherid

因为一对多的映射,几乎上都是通过Set来处理,所以多对多也是如此。首先生成POJO类,然后配置xml文件
其中的 Student.hbm.xml
 1<hibernate-mapping>
 2    <class name="org.jia.Student" table="student">
 3        <id name="studentid" type="integer">
 4            <column name="studentid" />
 5            <generator class="native" />
 6        </id>
 7        <property name="studentname" type="string">
 8            <column name="studentname" not-null="true" />
 9        </property>
10        <set name="teachers" table="stu_tea_relation" inverse="true"
11            cascade="all">
12            <key column="studentid"></key>
13            <many-to-many column="teacherid"
14                class="org.jia.Teacher">
15            </many-to-many>
16        </set>
17    </class>
18</hibernate-mapping>
//name="teacher"是指在Student.java中的那个set对象,以及相应的getter,stter方法的名字
//inverse是说明,是通过谁来管理谁,在此为true,说明是通过老师来选学生
<set name="teachers" table="stu_tea_relation" inverse="true"    cascade="all">
   <key column="studentid"></key>
   <many-to-many column="teacherid"
    class="org.jia.Teacher">
   </many-to-many>
  </set>
同样的Teacher.hbm.xml
<hibernate-mapping>
    
<class name="org.jia.Teacher" table="teacher">
        
<id name="teacherid" type="integer">
            
<column name="teacherid" />
            
<generator class="native" />
        
</id>
        
<property name="teachername" type="string">
            
<column name="teachername" not-null="true" />
        
</property>
        
<set name="students" table="stu_tea_relation" inverse="false"
            cascade
="all">
            
<key column="teacherid"></key>
            
<many-to-many column="studentid"
                class
="org.jia.Student">
            
</many-to-many>
        
</set>
    
</class>
</hibernate-mapping>

posted on 2007-08-27 10:10 jiadong 阅读(199) 评论(0)  编辑  收藏 所属分类: HIBERNATE

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


网站导航: