java – 无法理解如何使用Hibernate正确删除字段

我的数据库中存在多对多关系(实体是参与者和事件)

//part of participant model
@ManyToMany(fetch = FetchType.LAZY , cascade = { CascadeType.PERSIST, CascadeType.MERGE})
    @JoinTable(name = "participant_event",
            joinColumns = {@JoinColumn(name = "participant_id")},
            inverseJoinColumns = {@JoinColumn(name = "event_id")})

//part of event model 
  @ManyToMany(fetch = FetchType.LAZY, mappedBy = "events", cascade = CascadeType.ALL)

此时,删除事件会导致删除所有要访问此事件的参与者.删除事件模型中的CascadeType.ALL会导致删除事件后没有结果(删除我的意思是.remove).删除事件并保留所有参与者的正确方法是什么?

代码是here

最佳答案 在多对多关联中,
CascadeType.REMOVE is not desirable,因为它删除了实际实体(不仅仅是它们关联的链接表条目).

删除关联的正确方法是分离实体:

public void removeEvent(Event event) {
    events.remove(event);
    event.setParticipant(null);
}

要删除活动,您必须从所有参与者中删除.为此你必须做这样的事情:

Event deletableEvent = ...;

for(Iterator<Participant> participantIterator = event.getParticipnts(); participantIterator.hasNext();) {
    Participant participant = participantIterator.next();
    participant.getEvents().remove(deletableEvent);
    participantIterator.remove();
}

entityManager.flush();
entityManager.remove(deletableEvent);
点赞