I have a problem removing the parent entity from the database. The code looks like this:
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: update or delete on table “parent” violates foreign key constraint “fk2f04da924aeb47d8” on table “child””. Is it not possible to cascade the delete of all children? How should you clear the tables otherwise?
The bulk delete operation is not cascaded. From the JPA 1.0 specification:
So if you want to use a bulk delete, you’ll have to do handle relations “manually” (i.e. to delete related entities first).
The other option would be to loop on the parent entities and to call
em.remove()(and cascading would work).Choosing one option or the other will depend on the number of entities to delete and the expected performances.