[英]Hibernate generate additional query in ManyToMany relation while no CascadeType.REMOVE is set
I have the entity User
: 我有实体
User
:
@Entity
@Table(name = "users")
public class User {
(...)
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "users_roles",
joinColumns = @JoinColumn(name = "user_id", nullable = false),
inverseJoinColumns = @JoinColumn(name = "role_id", nullable = false)
)
private List<Role> roles;
}
and entity Role
with simple id
and name
columns. 和实体具有简单
id
和name
列的Role
。
User
and Role
have many-to-many relation with join table users_roles
. User
和Role
与连接表users_roles
具有多对多关系。
I have created method to remove a user: 我创建了删除用户的方法:
public void remove(long userId) {
Session session = getSession();
//NativeQuery joinTableQuery = session.createNativeQuery("DELETE FROM users_roles ur WHERE ur.user_id = :userId");
//joinTableQuery.setParameter("userId", userId);
//joinTableQuery.executeUpdate();
Query userQuery = session.createQuery("DELETE FROM User u WHERE u.id = :userId");
userQuery.setParameter("userId", userId);
userQuery.executeUpdate();
}
I have commented out first NativeQuery on purpose to check what happens. 我故意评论了第一个NativeQuery以检查发生了什么。 And what is interesting now Hibernate generates two queries:
现在有趣的是Hibernate会生成两个查询:
Question: 题:
Why does Hibernate generate additional query on users_roles
(join table) while my User
entity has no CascadeType.REMOVE
set on @ManyToMany
relation? 为什么Hibernate会在
users_roles
(连接表)上生成额外的查询,而我的User
实体在@ManyToMany
关系上没有设置CascadeType.REMOVE
? I thought I have to write it myself (commented part). 我想我必须自己写(评论部分)。
Your User
entity owns the many-to-many association to the Role
entity. 您的
User
实体拥有与Role
实体的多对多关联 。 When you remove a User
, Hibernate automatically also removes all entries from the association table. 删除
User
,Hibernate也会自动删除关联表中的所有条目。 But it doesn't cascade the remove operation to the Role
entity. 但它不会将删除操作级联到
Role
实体。
You should never use CascadeType.REMOVE
on a many-to-many association. 您不应该在多对多关联上使用
CascadeType.REMOVE
。 If you remove an entity, Hibernate will remove all associated entities even if they are still referenced by other entities. 如果删除实体,Hibernate将删除所有关联实体,即使它们仍被其他实体引用。 I explained that in great detail on my blog .
我在博客上详细解释了这一点。
If you would use CascadeType.REMOVE
on your roles
association and remove a User
, Hibernate would remove all Role
entities referenced by that User
. 如果您在
roles
关联上使用CascadeType.REMOVE
并删除User
,Hibernate将删除该User
引用的所有Role
实体。 It would do that even if there are other User
entity objects that are associated with these Role
s. 即使存在与这些
Role
相关联的其他User
实体对象,也会这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.