5
我們有以下兩個實體與許多-to-many關聯:如何一次刪除Hibernate JoinTable中的所有關聯?
@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中的所有關聯如this answer所示:
for (...)
{
A a = aDao.getObject(aId);
B b = bDao.getObject(bId);
b.getAs().remove(a);
a.getBs().remove(b);
bDao.saveObject(b);
}
有沒有辦法一次性刪除JoinTable中的所有關聯而無需迭代所有數據? 也許有一個特殊的HQL命令像DELETE Role.user_has_role
?