我们有以下两个具有多对多关联的实体:
@Entity
public class Role {
...
@ManyToMany
@JoinTable( name = "user_has_role", joinColumns = { @JoinColumn( name = "role_fk" ) }, inverseJoinColumns = { @JoinColumn( name = "user_fk" ) } )
private Set<User> userCollection;
...
}
和
@Entity
public class User {
...
//bi-directional many-to-many association to Role
@ManyToMany( mappedBy = "userCollection" )
private Set<Role> roleCollection;
...
}
如果我们想截断所有数据
em.createQuery( "DELETE Role" ).executeUpdate();
我们必须清除“user_has_role”JoinTable 中的所有关联,如此答案所示:
for ( ... )
{
A a = aDao.getObject(aId);
B b = bDao.getObject(bId);
b.getAs().remove(a);
a.getBs().remove(b);
bDao.saveObject(b);
}
有没有办法在不遍历所有数据的情况下一次删除 JoinTable 中的所有关联?也许有一个特殊的 HQL-Command 之类的DELETE Role.user_has_role
?