使用jpa存储库删除manytomany列表中的关系

时间:2014-03-20 17:23:31

标签: java jpa repository many-to-many jointable

我正在尝试在我的特定情况下在两个类(Account和Topic)之间设置多对多的关系。添加关系时,数据库中的相应表看起来很好,但是当要删除关系(保持两个对象)没有任何反应时,关系表看起来完全相同。

主题:

@Entity(name = "topic")
public class Topic implements Serializable{
    .
    .
    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "account_topic", joinColumns = { @JoinColumn(name = "topicId") }, inverseJoinColumns = { @JoinColumn(name = "accountId") })
    private List<Account> followers;
    .
    Getters and setters
    .
}

帐户:

@Entity(name = "account")
public class Account implements Serializable {
    .
    .
    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "account_topic", joinColumns = { @JoinColumn(name = "accountId") }, inverseJoinColumns = { @JoinColumn(name = "topicId") })
    private List<Topic> topics;
    .
    Getters and setters
    .
}

尝试删除关系失败:

@Autowired
private AccountRepository accountRepository;

@Autowired
private TopicRepository topicRepository;

public void removeTopicFromAccount(Long id, Long topicId) {
    Account account = accountRepository.findOne(id);
    Topic topic = topicRepository.findOne(topicId);
    account.getTopics().remove(topic);
    topic.getFollowers().remove(account);
    topicRepository.save(topic);
    accountRepository.save(account);
}

提前感谢您花时间帮助我!

1 个答案:

答案 0 :(得分:1)

尝试将注释更改为:

@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)