Hibernate在一对多

时间:2017-02-16 10:51:28

标签: java mysql hibernate

我有父实体,例如名为Parent,它扩展Base实体,我也有名为Children的子实体,并且在Parent中有一对多的关系,意思是Set<Children>,但是在Children中,parent被描述为Base,因此hibernate在子表中创建了两个外键,但最令人讨厌的是 - 其中一个是DELETE-CASCADE,而另一个不是,当我试图删除父项时会导致错误,我怎么能有一个外键(在父Parent中没有Children的严格关系{{1}或者至少修复违反密钥而不使用DELETE-CASCADE?

代码(不是全部,只是相对的)

Base.hbm.xml:

<class name="Base" table="controls">
    <id name="id">
    <subclass name="Parent" discriminator-value="Parent">
         <set name="items" cascade="save-update, delete-orphan" order-by="orderNumber asc" lazy="false" inverse="true" sort="natural">
             <key column="controlId" on-delete="cascade"/>
             <one-to-many class="children"/>
         </set>
     </subclass>
</class>

Children.hbm.xml:

<class name="controls.FAQItem" table="faq_item">
     <id name="id">
         <generator class="native"/>
      </id>
      <many-to-one name="base" column="controlId"/>
</class>

Parent.java:

public class Parent extends Base{
    private Set<Children> items;
    //getters  and setters
}

Children.class:

public class Children {
    private Base base;
    //getters and setters
}

错误:

    Cannot delete or update a parent row: a foreign key constraint fails 
(`db_cofp`.`children`, CONSTRAINT `FK3534269CB50AD2C` FOREIGN KEY (`controlId`) 
REFERENCES `controls` (`id`))

显示创建表格: *只是相对结束

KEY `FK3534269CC41202F7` (`controlId`),
KEY `FK3534269CB50AD2C` (`controlId`),
CONSTRAINT `FK3534269CB50AD2C` FOREIGN KEY (`controlId`) REFERENCES `controls` (`id`),
CONSTRAINT `FK3534269CC41202F7` FOREIGN KEY (`controlId`) REFERENCES `controls` (`id`) ON DELETE CASCADE

希望我向所有重要的事情表明,请注意BaseChildren使用id扩展BasicEntity类,没有写它,因为它只有int id和getter and setters < / p>

1 个答案:

答案 0 :(得分:0)

通过重写映射解决:

Base.hbm.xml:

<class name="Base" table="controls">
    <id name="id">
    <subclass name="Parent" discriminator-value="Parent">
         <set name="items" cascade="save-update, delete-orphan" order-by="orderNumber asc" lazy="false" sort="natural">
             <key column="controlId"/>
             <one-to-many class="children"/>
         </set>
     </subclass>
</class>

Children.hbm.xml:

<class name="controls.FAQItem" table="faq_item">
     <id name="id">
         <generator class="native"/>
      </id>
      <many-to-one name="base" column="controlId" class="Parent"/>
</class>