当父对象被删除时如何删除嵌套的Many to Many关联 - Hibernate JPA 2

时间:2017-01-16 06:20:44

标签: hibernate jpa hibernate-mapping jpa-2.1

以下是我的映射关系。

public class User {

    @Id
    @GeneratedValue
    @Column(name = "USER_ID")
    private Long userId;



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

    // Getter & Setters

}
 
public class UserGroup  {

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

    @ManyToMany(fetch = FetchType.EAGER,cascade=CascadeType.ALL)
    @JoinTable(name="GROUP_AUTHORITIES",joinColumns={@JoinColumn(name="GROUP_ID")}, inverseJoinColumns={@JoinColumn(name="AUTHORITY_ID")})
    private List<Authority> groupAuthorities;

    // Getter & Setters 

}
 
public class Authority {

    @Id
    @Column(name = "AUTHORITY_ID")
    private Long authorityId;
    @Column(name = "AUTHORITY_NAME")
    private String authorityName;

   // Getter & Setters 
}

当我删除User对象时,我只想删除关联的usergroups,但当与UserGroup.groupAuthorities匹配时,它会删除GROUP_ID的嵌套关系。

我希望在删除用户时避免此groupAuthorities删除,是否有可能做到这一点?

public void deleteUser(Long id) {

    User user = (User) getEntityManager().find(User.class, id);
    getEntityManager().remove(user);
    flush();

}

0 个答案:

没有答案