我有兩個實體上定義了許多一對多的關係。許多一對多和HQL批量刪除
<set name="TreasuryCodes" table="ServiceProviderAccountTreasuryCode" lazy="true" cascade="all">
<key column="ServiceProviderAccountId" />
<many-to-many column="TreasuryCodeId" class="TreasuryCode" />
</set>
<set name="ServiceProviderAccounts" table="ServiceProviderAccountTreasuryCode" lazy="true" inverse="true" cascade="all">
<key column="TreasuryCodeId" />
<many-to-many column="ServiceProviderAccountId" class="ServiceProviderAccount" />
</set>
現在我想通過ServiceProviderId刪除所有ServiceProviderAccounts。我寫這篇文章的代碼:
public void DeleteAllAccount(int serviceProviderId)
{
const string query = "delete ServiceProviderAccount spa where spa.ServiceProvider.Id = :serviceProviderId";
repository.Session.CreateQuery(query)
.SetInt32("serviceProviderId", serviceProviderId)
.ExecuteUpdate();
repository.Session.Flush();
}
,我收到此異常:
Test method Test.ServiceRepositoryTest.DeleteAllAccountTest threw exception:
NHibernate.Exceptions.GenericADOException: could not execute update query[SQL: delete from ServiceProviderAccount where ServiceProviderId=?] ---> System.Data.SqlClient.SqlException: The DELETE statement conflicted with the REFERENCE constraint "FKBC88A84CB684BF79". The conflict occurred in database "Test", table "dbo.ServiceProviderAccountTreasuryCode", column 'ServiceProviderAccountId'.
The statement has been terminated.
我很困惑,因爲我已經對實體定義的級聯,不應NHibernate的從ServiceProviderAccountTreasuryCode刪除行?
UPDATE
OK,貌似executeUpdate的不是找NHibernate的級聯反應,可能是因爲它沒有刪除之前加載實體?反正是有任何其他方式從ServiceProviderAccountTreasuryCode表,然後通過HQL從ServiceProviderAccounts刪除?我知道我可以在數據庫上使用級聯,但我想避免這種情況。我要的是HQL刪除許多-to-many關聯錶行。可能嗎?或者我應該使用普通的SQL?
是的,我做了一些研究,看起來像你的解決方案是唯一的。謝謝 – Davita 2011-02-27 08:49:07