开发者

How to delete all associations in a Hibernate JoinTable at once?

开发者 https://www.devze.com 2023-01-08 18:21 出处:网络
We have the following two entities with many-to-many association: @Entity public class Role { ... @ManyToMany

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 ?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消