一尘不染

关于删除级联休眠ManyToMany

hibernate

我希望UserAcounts可以有许多UserGroups,而所有Groups可以有许多Users。还有一个联接表。我希望在删除useraccount时删除联接表中useraccount和usergroup之间的关系。

实际上,我想使用“在删除级联上”。在ManyToMany关系中,我不会不幸地运行它。我已经尝试了很多事情,但没有找到解决方案。

注意:我只想在删除级联上删除关系

是否有办法做到这一点?

这是我的hibernate课程

@SuppressWarnings("serial")
@Entity
@Table(name = "USER_ACCOUNT")
public class UserAccount implements Serializable {

@Id
@Column(name = "ID")
@GeneratedValue
private Long id;

@Column(name = "NAME")
private String name;

@Column(name = "SURNAME")
private String surname;

@Column(name = "EMAIL")
private String email;

@Column(name = "USER_NAME")
private String username;

@Column(name = "PASSWORD")
private String password;

@Column(name = "ENABLED")
@Type(type = "yes_no")
private boolean enabled;

@Column(name = "ACCOUNT_NON_EXPIRED")
@Type(type = "yes_no")
private boolean accountNonExpired;

@Column(name = "CREDENTIALS_NON_EXPIRED")
@Type(type = "yes_no")
private boolean credentialsNonExpired;

@Column(name = "ACCOUNT_NON_LOCKED")
@Type(type = "yes_no")
private boolean accountNonLocked;

@Column(name = "ENTRY_DATE")
private Date entryDate;

@Column(name = "UPDATE_DATE")
private Date updateDate;

@Column(name = "LAST_LOGIN_DATE")
private Date lastLoginDate;

@Column(name = "LOCAL")
private String local;

@ManyToMany(cascade = CascadeType.ALL,fetch=FetchType.EAGER)
@JoinTable(name = "ACCOUNT_GROUP", joinColumns = { @JoinColumn(name = "ID") }, inverseJoinColumns = { @JoinColumn(name = "GROUP_ID") })
private List<UserGroup> userGroups;








@SuppressWarnings("serial")
@Entity
@Table(name = "USER_GROUP")
public class UserGroup implements Serializable {

@Id
@Column(name = "GROUP_ID")
@GeneratedValue
private Long id;

@Column(name = "GROUP_NAME")
private String name;

@Column(name = "GROUP_DESCRIPTION")
private String description;

我研究了太多,但无法运行。


阅读 271

收藏
2020-06-20

共1个答案

一尘不染

设置为DELETE的级联在删除用户时不会删除组和用户之间的关联。它将删除组本身。

要删除关联,只需在删除用户之前从用户组集合中删除所有组:

user.getUserGroups().clear();
session.delete(user);

从用户中删除组将删除联接表中的关联。

2020-06-20