我已经阅读了很多关于级联和多对多关联的主题,但我一直无法找到我的特定问题的答案。
我在 UserProfiles 和 Roles 之间存在多对多关系。当我删除 UserProfile 时,我希望数据库删除连接表 (userprofile2role) 中的关联记录,因此使用实际的 SQL 'ON DELETE CASCADE' 操作。这可能吗?无论我尝试什么,Hibernate 总是在不指定 ON DELETE 行为的情况下创建 UserProfile 表。
用户配置文件映射:
@Entity
public class UserProfile {
private Long id;
private Set<Role> roles;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public final Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
// Note: CascadeType.ALL doesn't work for many-to-many relationships
@ManyToMany (fetch = FetchType.EAGER)
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
角色映射:
@Entity
public class Role {
private Long id;
private Set<UserProfile> userProfiles = new HashSet<UserProfile>();
@Id
@GeneratedValue
public final Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
// CascadeType.REMOVE doesn't create ON CASCADE DELETE in SQL?
@ManyToMany(mappedBy = "roles", cascade = CascadeType.REMOVE)
public Set<UserProfile> getUserProfiles() {
return userProfiles;
}
public void setUserProfiles(Set<UserProfile> userProfiles) {
this.userProfiles = userProfiles;
}
}
不幸的是,由这些映射产生的连接表的 SQL 不包含 ON CASCADE DELETE 部分。我尝试在 UserProfile 中的角色集合和 Role 中的 userprofiles 集合上设置 CascadeType.REMOVE 行为(如图所示),但无济于事。非常欢迎您的建议:-)
CREATE TABLE `px_userprofile2role` (
`userprofile_id` BIGINT(20) NOT NULL,
`role_id` BIGINT(20) NOT NULL,
PRIMARY KEY (`userprofile_id`,`role_id`),
KEY `FK1C82E84191F65C2B` (`userprofile_id`),
KEY `FK1C82E8416203D3C9` (`role_id`),
CONSTRAINT `FK1C82E8416203D3C9` FOREIGN KEY (`role_id`) REFERENCES `px_role` (`id`),
CONSTRAINT `FK1C82E84191F65C2B` FOREIGN KEY (`userprofile_id`) REFERENCES `px_userprofile` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=latin1
最佳答案
不支持生成 ON DELETE CASCDADE
到 JPA 中的 DDL。级联 REMOVE 操作的概念不是 DDL 级别的构造。级联是关于将针对实体的生命周期操作级联到相关实体。它们与数据库中的级联几乎没有关系。在 JPA 2.0 规范中,这解释如下:
If X is a new entity, it is ignored by the remove operation. However, the remove operation is cascaded to entities referenced by X, if the relationship from X to these other entities is annotated with the cascade=REMOVE or cascade=ALL annotation element value.
If X is a managed entity, the remove operation causes it to become removed. The remove operation is cascaded to entities referenced by X, if the relationships from X to these other entities is annotated with the cascade=REMOVE or cascade=ALL annotation element value.
此外 REMOVE 不应与 @ManyToMany 一起使用(来自 JPA 2.0 规范):
The relationship modeling annotation constrains the use of the cascade=REMOVE specification. The cascade=REMOVE specification should only be applied to associations that are specified as OneToOne or OneToMany. Applications that apply cascade=REMOVE to other associations are not portable.
产生什么
ON DELETE CASCDADE
到 DDL,有供应商扩展 @OnDelete在 hibernate 中:@OnDelete(action=OnDeleteAction.CASCADE)
关于hibernate - JPA2 多对多关系上的级联删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16502481/