views:

59

answers:

1

Hi,

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?

+1  A: 

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

4.10 Bulk Update and Delete Operations

(...)

A delete operation only applies to entities of the specified class and its subclasses. It does not cascade to related entities.

(...)

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.

Pascal Thivent
So you mean that I have to load all the parent objects (and all children and children's children) so that I can remove them?!
Peter Eriksson
Isn't it possible ask JPA (Hibernate) to recreate all tables? It can do it at application server start up, so why not when running?Or truncate or something?
Peter Eriksson
@Peter I never said it wasn't possible to recreate all tables, this is just a totally different question (recreating all tables vs deleting one). You can use `SchemaExport` for that. See this [previous answer](http://stackoverflow.com/questions/3121743/easy-way-to-truncate-all-tables-clear-first-and-second-level-hibernate-cache/3121963#3121963).
Pascal Thivent