Question

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.

Was it helpful?

Solution

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top