为什么Hibernate将外键设置为空值?

时间:2012-06-22 15:40:21

标签: hibernate

我使用的是Hibernate 3.0.5,Java 6,MySQL 5.5。我以为我已经正确设置了一切,但显然我没有。

以下是类映射:

<class name="com.rc.model.partner.Partner" table="partner">
    ...
    <set name="pacChannelSet" table="pac_channel" lazy="false" cascade="all">
        <key column="partnerid"/>
        <one-to-many class="com.rc.model.partner.PacChannel"/>
    </set>
</class>

<class name="com.rc.model.partner.PacChannel" table="pac_channel">
    ...
    <many-to-one name="partner" class="com.rc.model.partner.Partner" column="partnerid"
                 foreign-key="partnerid" cascade="none"/>
</class>

这是Java代码:

pacChannelDAO.saveOrUpdate(pacChannel1);
partner.addPacChannel(pacChannel1);
pacChannelDAO.saveOrUpdate(pacChannel2);
partner.addPacChannel(pacChannel2);
partnerDAO.saveOrUpdate(partner);

以下是调试语句,表示尝试使pac_channel表中的partnerid无效,并产生错误:

11:27:07,088 DEBUG [SQL] update partner set ... where partnerid=? and updateddate=?
11:27:07,165 DEBUG [SQL] update pac_channel set partnerid=?, channelname=?, apikey=?, active=?, dailyrequestlimit=? where pacchannelid=?
11:27:07,193 DEBUG [SQL] update pac_channel set partnerid=?, channelname=?, apikey=?, active=?, dailyrequestlimit=? where pacchannelid=?
11:27:07,300 DEBUG [SQL] update pac_channel set partnerid=null where partnerid=? and pacchannelid=?
11:27:07,413 ERROR [JDBCExceptionReporter] Cannot add or update a child row: a foreign key constraint fails (`mexp`.`pac_channel`, CONSTRAINT `chan_partnerid_fk` FOREIGN KEY (`partnerid`) REFERENCES `partner` (`partnerid`) ON DELETE NO ACTION ON UPDATE NO ACTION)

为什么Hibernate使用“set partnerid = null”生成最后一个SQL语句?任何见解将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

我从不使用XML来映射我的实体,但我认为你的映射是错误的。一方应该是多方的反面,如the documentation

所示
<class name="Person">
    <id name="id" column="personId">
        <generator class="native"/>
    </id>
    <many-to-one name="address" 
        column="addressId"
        not-null="true"/>
</class>

<class name="Address">
    <id name="id" column="addressId">
        <generator class="native"/>
    </id>
    <set name="people" inverse="true">
        <key column="addressId"/>
        <one-to-many class="Person"/>
    </set>
</class>