How to remove all associations in Hibernate JoinTable at once?

We have the following two objects with a 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 crop all data with

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

we need to clear all associations in the "User_has_role" JoinTable, as 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 remove all associations in JoinTable at once without iterating over all the data? Maybe there is a special HQL command, for example DELETE Role.user_has_role?

+5
source share
1 answer

JPA , ( 4.10 " " ), , . , Hibernate , HHH-1917. : SQL.

+3

All Articles