我有非常简单的架构 - 一对多关系中的两个表:
<hibernate-mapping package="my.app">
<class name="CorrelationKey" table="CORRELATION_KEYS">
<id name="id" column="CORRELATION_ID">
<generator class="native"/>
</id>
<set name="correlationKeyParts" cascade="all-delete-orphan" lazy="false">
<key column="CORRELATION_ID"/>
<one-to-many class="CorrelationKeyPart"/>
</set>
...
</class>
</hibernate-mapping>
保存和更新CorrelationKey
类型的对象正常工作,并将更改传播到集合。但是当我尝试删除CorrelationKey
对象时,我收到以下错误:
108090 [main] ERROR org.hibernate.util.JDBCExceptionReporter - ERROR: update or
delete on table "correlation_keys" violates foreign key constraint "fk23630e23e9b29c52"
on table "correlation_key_parts"
Detail: Key (correlation_id)=(162) is still referenced from table "correlation _key_parts".
我在Windows机器上使用PostgreSQL 9.1。
非常感谢。
答案 0 :(得分:2)
执行这样的DML查询时,会完全绕过会话缓存,级联和版本检查。查询直接转换为SQL查询并按原样执行。因此,您有责任首先删除(或修改)从属实体。如果要应用级联,则需要使用Hibernate API:
List<CorrelationKey> allKeys = session.createQuery("select k from CorrelationKey k").list();
for (CorrelationKey key : allKeys) {
session.delete(key);
}