Can't figure out how to delete fields correctly using Hibernate

I have a many-to-many relationship in my database (objects are Participant and Event)

//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)

Currently, deleting an event will delete all participants who will attend this event. Deletion CascadeType.ALLin the event model does not produce a result after deleting an event (by deletion, I mean .remove). How can I delete an event only and save all participants?

Code here

+4
source share
1 answer

"--" CascadeType.REMOVE , ( ).

, :

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

Event, Participants. - :

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);
+2

Source: https://habr.com/ru/post/1584719/


All Articles