我希望UserAcounts能够拥有多个UserGroup。并且所有组都可以拥有多个Users.And有一个连接表。我希望在删除useraccount时删除连接表中useraccount和usergroup之间的关联。 / p>
实际上我想使用“删除级联”。在ManyToMany关系中,我不幸运行它。我已经尝试了很多东西,但我找不到解决方案。
注意:我只想在删除级联
上删除Relation有可能有办法吗?
这是我的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;
我研究得太多但我无法运行它。
答案 0 :(得分:5)
设置为DELETE的级联在删除用户时不会删除组与用户之间的关联。它会自己删除这些组。
要删除关联,您只需在删除用户之前从用户组中删除所有组:
user.getUserGroups().clear();
session.delete(user);
从用户中删除组将删除连接表中的关联。
答案 1 :(得分:0)
JB Nizet的示例非常适合删除多个实体的关联。我不得不删除30万个协会。在这种情况下,可能最好使用SQLQuery,即使它不是Hibernate友好的(并且你使用本机SQL语言并不漂亮)。由于性能问题,可能有必要。
SQLQuery queryDeleteDisabled = getSession().createSQLQuery("delete from ACCOUNT_GROUP where ID in (select ID from USER_ACCOUNT where ENABLED=?)");
queryDeleteDisabled.setParameter(0, false);
int nbDelete = queryDeleteDisabled.executeUpdate();