Removing a parent and all children

I have a problem deleting the parent from the database. The code is as follows:

public class Parent implements Serializable {
  @Id
  @GeneratedValue(strategy = GenerationType.TABLE)
  private Long id;  

  @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
  @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
  @JoinColumn(name="parentId")
  private Set<Child> children = new HashSet<Child>();
}

public class Child implements Serializable {
  @Id
  @GeneratedValue(strategy = GenerationType.TABLE)
  private Long id;  

  private String name;
}


Query q = em.createQuery("delete from Parent");
q.executeUpdate();

But I get “ERROR: updating or deleting in the parent table violates the foreign key constraint of fk2f04da924aeb47d8 on the child table. Is it impossible to cascade the deletion of all children? How to clear the tables otherwise?

+3
source share
1 answer

The bulk delete operation is not cascaded. From the JPA 1.0 specification:

4.10 Bulk update and delete operations

(...)

. .

(...)

, , "" (.. ).

​​ em.remove() ( ).

.

+1

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


All Articles