Hibernate Panel Cascade Delete Collection

Unfortunately, Oracle (at least the version I'm using) does not support automatic cascading deletes. Should child records be deleted separately before parent records are deleted in order to avoid restriction violations?

When deleting the parent object with the CascadeType.DELETE parameter on @OneToMany, when Hibernate decides to delete each child instance one by one and delete by foreign key in the package.

For instance,

PARENT table:

PARENT_ID

1

2

CHILD:

CHILD_ID PARENT_ID

eleven

2 1

3 2

Removing a parent can cascade the removal of children in two ways:

delete from CHILD where child_id = 1
delete from CHILD where child_id = 2
delete from PARENT where parent_id = 1

or

delete from CHILD where parent_id = 1
delete from PARENT where parent_id = 1

, Hibernate . , Hibernate , . , , , . , ConstraintViolationException, , .

+3
1

Hibernate . :

"Oracle ( , , ) "

.

:

SQL> create table parent (id)
  2  as
  3  select 1 from dual union all
  4  select 2 from dual
  5  /

Table created.

SQL> alter table parent
  2    add constraint parent_pk
  3    primary key (id)
  4  /

Table altered.

SQL> create table child (id, parent_id)
  2  as
  3  select 1, 1 from dual union all
  4  select 2, 1 from dual union all
  5  select 3, 2 from dual
  6  /

Table created.

SQL> alter table child
  2    add constraint child_pk
  3    primary key (id)
  4  /

Table altered.

, , :

SQL> alter table child
  2    add constraint child_parent_fk
  3    foreign key (parent_id)
  4    references parent(id)
  5  /

Table altered.

, :

SQL> delete parent
  2   where id = 1
  3  /
delete parent
*
ERROR at line 1:
ORA-02292: integrity constraint ([schema].CHILD_PARENT_FK) violated - child record found

ON DELETE CASCADE...

SQL> alter table child
  2    drop constraint child_parent_fk
  3  /

Table altered.

SQL> alter table child
  2    add constraint child_parent_fk
  3    foreign key (parent_id)
  4    references parent(id)
  5    on delete cascade
  6  /

Table altered.

... :

SQL> select * from parent
  2  /

        ID
----------
         1
         2

2 rows selected.

SQL> select * from child
  2  /

        ID  PARENT_ID
---------- ----------
         1          1
         2          1
         3          2

3 rows selected.

SQL> delete parent
  2   where id = 1
  3  /

1 row deleted.

SQL> select * from parent
  2  /

        ID
----------
         2

1 row selected.

SQL> select * from child
  2  /

        ID  PARENT_ID
---------- ----------
         3          2

1 row selected.

, .

+2

Source: https://habr.com/ru/post/1782454/


All Articles