Reputation: 593
I have two entities: User and Event. Each user has a list of events that he pay attention to.
@Entity
@Table(name = "user")
public class User {
@Id
@Column(name = "login", length = 64)
protected String login;
@ManyToMany
@LazyCollection(LazyCollectionOption.FALSE)
@JoinTable(name = "user_events",
joinColumns = {@JoinColumn(name = "login") },
inverseJoinColumns = {@JoinColumn(name = "event_id") })
protected List<Event> events;
}
@Entity
@Table(name = "events")
public class Event extends BaseEntity {
@Id
@Column(name = "event_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long eventId;
}
But when a user pay attention to an event, then I can't delete that event from the database. It seems there is some restriction set by the JPA. Could anyone tell me how to fix that? Thank you in advance.
Upvotes: 0
Views: 293
Reputation: 691865
Th restriction is not set by JPA. It's in your database: the event_id
join column in the join table is a foreign key to the ID of the event. You may not remove the event because some user is still referencing it.
If you want to delete the event, and also delete all the references from users to the event, then you must search for all the users referencing the event, remove the event from their list, and then delete the event.
String jpql = "select u from User u inner join u.events e where e.id = :eventId;
// execute the query
for (User u : users) {
u.removeEvent(eventToDelete);
}
em.remove(eventToDelete);
Upvotes: 2