Hibernate中如何处理一对多关系中的组合主键

前段时间碰到这个问题,主要是hbm文件的的写法问题。我建了两个表,parent中的Pid与child中的Cid是一对多关系,Child中的cid与otherid只组合主键.如下

parent

字段名       

类型

长度

Pid  (PK)

Character

10

Name

Character

10

 Child

字段名   

类型

长度

cid       (PK)

Character

10

Otherid    (PK)

Smallint

 <?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Name

Character

10

hbm文件:

Parent.hbm.xml

<?xml version="1.0" encoding="GB2312"?>
<!DOCTYPE hibernate-mapping PUBLIC
   "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping>
<class name="Parent" table="parent">
<id
            name="pid"
            column="pid"
            type="string"
            unsaved-value="any"
        >
            <generator class="assigned"/>
        </id>
<property name="name"/>
<set name="children" cascade="all-delete-orphan" inverse="true" lazy="true" >
        <key column="CID" />
        <one-to-many class="Child"/>
 </set>
</class>
</hibernate-mapping>

Child.hbm.xml

<?xml version="1.0" encoding="GB2312"?>
<!DOCTYPE hibernate-mapping PUBLIC
   "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping>
<class name="Child" table="child">
<composite-id name="childpk" class="Childpk" unsaved-value="any">
<key-many-to-one name="parent" class="Parent" column="cid" />
<key-property name="otherid" column="otherid" type="integer"/>
</composite-id>
<many-to-one name="parent" class="Parent" column="CID" cascade="save-update" not-null="true" update="false" insert="false" />
<property name="name" column="name" type="string" />
</class>
</hibernate-mapping>

这两个hbm文件里面主要是:Parent中的<set name="children" cascade="all-delete-orphan" inverse="true" lazy="true" >
        <key column="CID" />
        <one-to-many class="Child"/>
 </set> 和Child中的<many-to-one name="parent" class="Parent" column="CID" cascade="save-update" not-null="true" update="false" insert="false" />

这两个构成一对多关系中组合主键的双向关联。另外在写PO类的时候要注意hashcode和equals写的正确

 

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页