문제

I have very simple schema - two tables in one-to-many relationship:

<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>

Saving and updating objects of type CorrelationKey work correctly and the changes as propagated to the set. But when I try to delete a CorrelationKey object I get the following error:

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".

I am using PostgreSQL 9.1 on Windows machine.

Many thanks.

도움이 되었습니까?

해결책

When you execute a DML query like this, the session cache, the cascades and the version checks are completely bypassed. The query is directly translated into a SQL query and executed as is. So it's your responsibility to delete (or modify) the dependant entities first. If you want the cascade to apply, you need to use the Hibernate API:

List<CorrelationKey> allKeys = session.createQuery("select k from CorrelationKey k").list();
for (CorrelationKey key : allKeys) {
    session.delete(key);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top