views:

105

answers:

1

We have the following two entities with many-to-many association:

@Entity
public class Role {
  ...
  @ManyToMany
  @JoinTable( name = "user_has_role", joinColumns = { @JoinColumn( name = "role_fk" ) }, inverseJoinColumns = { @JoinColumn( name = "user_fk" ) } )
  private Set<User>           userCollection; 
  ...
}

and

@Entity
public class User {
  ...
  //bi-directional many-to-many association to Role
  @ManyToMany( mappedBy = "userCollection" )
  private Set<Role>        roleCollection;
  ...
}

If we want to truncate all data with

em.createQuery( "DELETE Role" ).executeUpdate();

we have to clear all associations in the "user_has_role" JoinTable like shown in this answer:

for ( ... )
{
    A a = aDao.getObject(aId);
    B b = bDao.getObject(bId);

    b.getAs().remove(a);
    a.getBs().remove(b);
    bDao.saveObject(b); 
}

Is there a way to do delete all associations in the JoinTable at once without iterating over all the data? Maybe there is a special HQL-Command like DELETE Role.user_has_role ?

+2  A: 

While the JPA spec clearly writes that bulk operations are not cascaded to related entities (section 4.10 Bulk Update and Delete Operations), I expect providers to deal at least with join tables. Sadly, Hibernate doesn't and this is logged in HHH-1917. Workaround: use native SQL.

Pascal Thivent