Reputation: 10418
I want to define my @ManyToMany relationship with JPA Annotations so that relations are not removed when updating entity.
@ManyToMany(targetEntity=Event.class, cascade={CascadeType.ALL}, fetch = FetchType.LAZY)
@JoinTable(
name = "event_user",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "event_id")
)
private Set<Event> events;
and Event class
@ManyToMany(cascade = {CascadeType.ALL}, mappedBy="events", targetEntity=User.class, fetch = FetchType.LAZY)
private Set<User> attending;
I thought setting CascadeType.REMOVE would not trigger deletion when updating but when I call update on a user object, all its related events are removed.
This is from my DAO
@Override
public User update(User entity) {
sessionFactory.getCurrentSession().update(entity);
return entity;
}
When I call update on my entity, Hibernate does:
Hibernate: delete from event_user where user_id=?
Upvotes: 2
Views: 1434
Reputation: 2625
The comments on your questions are correct so far. You obviously do not load the entity from the database before updating it. Hence, hibernate updates everything just as it finds it in your entity. So, load the entity (by id?), merge your changes and update it afterwards.
Btw you should also consider using the delete orphans annotation. You would hence make sure that events to a user would also get deleted when setting the event collection to null and not only when removing the entire user.
Upvotes: 1