aminedev
aminedev

Reputation: 323

OnDelete cascade fails with constraint violation error () Hibernate

    <id name="idInstance" type="java.lang.Integer">
        <column name="ID_INSTANCE" />
        <generator class="native" />
    </id>


    <property name="nom" type="string">
        <column name="NOM" length="50" not-null="true" />
    </property>

            <property name="description" type="string">
        <column name="DESCRIPTION" length="300" not-null="true" />
    </property>

    <set name="statistiques" cascade="all" lazy="false">
        <key column="ID_INSTANCE"></key>
        <one-to-many class="Statistique" />
    </set>
        </class>

and the hbm file of class statistique is :

<class name="Statistique" table="STATISTIQUE">

    <id name="idStatistique" type="java.lang.Integer">
        <column name="ID_STATISTIQUE"/>
        <generator class="native" />
    </id>

    <property name="tempsReponse" type="java.lang.Double">
        <column name="TEMPS_REPONSE"/>
    </property>

    <property name="date" type="timestamp">
        <column name="DATE"/>
    </property>

</class>

If the statistiques list is empty, this seems to be working fine. It fails with a foreign key violation error :

Integrity constraint violation FKD18D3C4EDC6F4BFB table: STATISTIQUE in statement [delete from INSTANCE_Monitor where (ID_INSTANCE) IN (select ID_INSTANCE from HT_INSTANCE_Monitor)]

Upvotes: 0

Views: 900

Answers (2)

Johanna
Johanna

Reputation: 5293

You probably have a constraint in the database which demands for every row in statistique the existence of the row in instance_monitor. Before you can delete rows in instance_monitor, you have to delete the appertaining rows in statistique.

The clause cascade="all" does not imply a cascade delete on database level. It just forces hibernate to generate explicit delete statements for the child table (statistique in your case). The problem is, the delete statements may arrive in an order which is not compatible with your database constraint. This also can happen due to hibernate's re-ordering of database statements.

What you can do: Either remove the database constraint (if possible) or

  1. Delete the rows from the statistique table, which belong to the instance_monitor "manually ("i. e. with separate delete statements)
  2. Call session.flush() (prevents against the statement re-ordering by hibernate)
  3. delete the instance_monitor

Upvotes: 1

Kshitij
Kshitij

Reputation: 8614

If the statistiques list is empty, this seems to be working fine. It fails with a foreign key violation error :

You seem to have not enabled cascade delete at database level.

Upvotes: 0

Related Questions