我們有三個表TABLE_A,TABLE_B和TABLE_C。 A & B與外鍵具有一對一映射(兩個表具有相同的主ID)。 B & C有一對多的關係。我已經定義瞭如下的hibernate映射。HIbernate一對多映射刪除不工作
<class name="com.test.ClassA" table="TABLE_A">
<id name="aId" type="long">
<column name="A_ID" />
<generator class="assigned" />
</id>
<one-to-one name="classB" class="com.test.ClassB" cascade="all" lazy="false"/>
</class>
<class name="com.test.classB" table="TABLE_B">
<id name="aId" type="long">
<column name="A_ID" />
<generator class="assigned"/>
</id>
<one-to-one name="classA" class="com.test.ClassA" constrained="true"/>
<set name="listOfC" table="TABLE_C" inverse="false" lazy="false" fetch="select" cascade="all-delete-orphan">
<key>
<column name="A_ID" not-null="true"/>
</key>
<one-to-many class="com.test.ClassC"/>
</set>
</class>
<class name="com.test.ClassC" table="TABLE_C">
<id name="id" type="long">
<column name="ID" />
<generator class="identity"/>
</id>
<many-to-one name="classB" class="com.test.ClassB" fetch="select">
<column name="A_ID"/>
</many-to-one>
</class>
當我嘗試插入/更新ClassA的,B和C得到保存。但是,試圖刪除答:當我得到約束違反異常
得到&刪除邏輯
public ClassA getClassA(final long aID)throws HibernateException, SQLException
{
HibernateCallback callback = new HibernateCallback()
{
public Object doInHibernate(Session session) throws HibernateException, SQLException
{
Criteria hctr = session.createCriteria(ClassA.class);
hctr.add(Restrictions.eq("A_ID", aID));
return hctr.list();
}
};
List list = (List)this.getHibernateTemplate().execute(callback);
if(list==null || list.size()==0)
{
return null;
}
return (ClassA)list.get(0);
}
公共無效deleteClassA(長AID)拋出HibernateException的,的SQLException { ClassA的CLASSA = getClassA(AID) ; if(classA!= null) this.getHibernateTemplate()。delete(classA); } }
更新TABLE_C設置A_ID = NULL其中A_ID =];約束[null];嵌套0例外是org.hibernate.exception.ConstraintViolationException: 無法刪除收集:在 org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException [com.test.ClassB.listOfC#77675](SessionFactoryUtils.java:659) 在 org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:414) 在 org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:416) 在 org.springframework.orm。 hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:379) at org.springframework.orm.hibernate3.HibernateTemplate.delete(Hiberna teTemplate.java:887) at org.springframework.orm.hibernate3.HibernateTemplate.delete(HibernateTemplate.java:882) 引起:com.ibm.db2.jcc.am.oo:將NULL值分配給 NOT NULL列 「TBSPACEID = 3,TABLEID = 480,COLNO = 1」 是不允許.. SQLCODE = -407,SQLSTATE = 23502,DRIVER = 3.58.81
出於某種原因,休眠正試圖用NULL值更新TABLE_C條目而不是刪除它。我觀察到的一件事是,當使用getClassA()函數加載classA時,ClassC中的「aId」值爲null。我已經驗證了該表並且該值確實存在。從數據庫讀取時不知道爲什麼它爲空。