【问题标题】:How to delete entities in many-to-many relationship in Hibernate如何在 Hibernate 中删除多对多关系中的实体
【发布时间】:2020-01-23 01:36:03
【问题描述】:

我有两个实体类:帐户和角色。这些映射与多对多关系。我想从数据库中删除一个帐户。下面的代码对我有用,但是,我相信有更好的方法。

我的Account.class

public class Account {

    //some code

    @ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.MERGE, CascadeType.PERSIST})
    @JoinTable(name = "account_role",
            joinColumns = {@JoinColumn(name = "account_id")},
            inverseJoinColumns = {@JoinColumn(name = "role_id")})
    private Set<Role> roles = new HashSet<>();

}

我的Role.class

public class Role {

    //some code

    @EqualsAndHashCode.Exclude
    @ManyToMany(mappedBy = "roles", fetch = FetchType.EAGER,
             cascade = {CascadeType.MERGE , CascadeType.PERSIST/*, CascadeType.DETACH, CascadeType.REFRESH*/})
    private Set<Account> accounts = new HashSet<>();
}

这是我在 PostgreSQL 中的映射

TL;DR

下面的代码运行良好,有什么更好的方法?

@Override
public void deleteUserAndHisTokensById(Long accountId) {
    Account accountToBeDelete = accountRepository.findDistinctById(accountId);
    accountToBeDelete.getRoles()
            .forEach(role -> {
                Set<Account> updatedAccounts = role.getAccounts()
                        .stream()
                        .filter(account -> !account.equals(accountToBeDelete))
                        .collect(Collectors.toSet());
                role.setAccounts(updatedAccounts);
                roleRepository.save(role);
            });
     
        accountToBeDelete.setRoles(null);
        accountRepository.deleteById(accountId);
    }

【问题讨论】:

  • Role 关系中添加cascade = { ...., ...., CascadeType.REMOVE},然后仅使用accountRepo.deleteById(accountId); 并将被删除。

标签: java spring hibernate spring-boot many-to-many


【解决方案1】:

如果您添加CascadeType.REMOVE,就像@JonathanJohx 提到的那样。您可以像这样删除它:

accountRepository.deleteById();

此外,如果您想从帐户中删除角色,请将 CascadeType.REMOVE 添加到关系的另一端,这样您就可以这样做:

Role role = roleRepository.findById(10);
Account account = accountRepository.findById(11);
account.getRoles().remove(role);

【讨论】:

  • 感谢您的提及,所以这里是upvoted。 :)
  • 看起来很奇怪,但是添加级联删除对我没有帮助。我正在帐户上尝试->如果我删除帐户,它可以工作并删除帐户和角色。如果我只是调用角色,则添加 REMOVE 级联什么都不做: accountRepo.deleteDistinctById(someId); P.s thx 在我的帖子中提高英语等
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 2012-10-10
  • 2018-07-04
  • 1970-01-01
相关资源
最近更新 更多