我有两个实体父母和孩子。父母只能有一个孩子。当我保存父母时,我得到一个 CONSTRAINT VIOLATION 异常。
那么,为什么 Hibernate 在保存父实体之前不保存子实体呢?
用于保存父级的 Java 代码:
Child c = new Child();
c.setId(1);
Parent p = new Parent();
p.setId(4);
p.setChild(c);
父 hbm.xml 文件:
<hibernate-mapping default-cascade="all">
<class name="com.ParentImpl" table="Parent" dynamic-insert="false" dynamic-update="false">
<cache usage="read-write" />
<id name="id" type="java.lang.Long" unsaved-value="null">
<column name="ID" sql-type="BIGINT"/>
</id>
<many-to-one name="child" class="com.ChildImpl" foreign-key="CHILDFKC" cascade="all" lazy="false" fetch="select">
<column name="CHILD_FK" not-null="true" sql-type="BIGINT" unique="true"/>
</many-to-one>
</class>
</hibernate-mapping>
孩子-hbm-.xml
<hibernate-mapping default-cascade="all">
<class name="ChildImpl" table="DATA_DELETION_PERIODS" dynamic-insert="true" dynamic-update="true">
<cache usage="read-write" />
<id name="id" type="java.lang.Long" unsaved-value="null">
<column name="ID" sql-type="BIGINT"/>
</id>
</class>
</hibernate-mapping>