Evgenii
Evgenii

Reputation: 447

Hibernate ManyToMany wtih column child removal

I have Many To Many with additional column. Here realization(getters/setters generated by lombok, removed for clarity):

public class User extends BaseEntity {
@OneToMany(mappedBy = "user",
        orphanRemoval = true,            
        fetch = FetchType.LAZY
        cascade = CascadeType.ALL,)
   private List<UserEvent> attendeeEvents = new ArrayList<>();
}

@Table(
        name = "UC_USER_EVENT",
        uniqueConstraints = {@UniqueConstraint(columnNames = {"user_id", "event_id"})}
)
public class UserEvent extends BaseEntity {

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "event_id")
    private Event event;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "user_response_id")
    private UserResponse userResponse;
}

public class Event extends BaseEntity { 
    @OneToMany(mappedBy = "event",
            orphanRemoval = true,
            fetch = FetchType.EAGER,
            cascade = CascadeType.ALL)
    private List<UserEvent> userEvents = new ArrayList<>();
}

I want this - when i delete Event, All "UserEvents" connected to it should be removed. And if I delete User, all "UserEvents" should be removed too.

I delete my event(eventRepository is Spring Jpa interface):

 eventRepository.delete(event);

Then retrieving UserEvents from db:

List<UserEvent> userEvents = userEventsId.stream()
.map(id -> entityManager.find(UserEvent.class, id)).collect(Collectors.toList());

And there is collection with 2 items(this is count of UserEvents), but they all "null".

I can't understand what happening and how to do it right. I need them deleted and when I check collection there should be 0, instead of 2.

Upvotes: 0

Views: 31

Answers (1)

Hans Poo
Hans Poo

Reputation: 924

The delete says marked for deletion, please try calling flush after deletion, and then find.

I guess find goes to the database, find the two rows, but when trying to instantiate them, find the entities marked for deletion and then you have this strange behaviour.

Recomendation: try to abstract more from the database and use less annotations. Learn the conventions of names for columns and tables (if you need to) and let JPA do its job.

Upvotes: 1

Related Questions