I use Spring Data JPA
and MySQL
. I have one to many relation between Event
and Category
. Obviously:
- one
Event
can have only oneCategory
- one
Category
can be assigned manyEvent
s.
The problem appears when I try to remove Category
, if any Event
hold a foreign key of this Category
then I get an error. I would like to set the foreign key in the Event
table to null
when a Category
is deleted.
At the moment I update all Event
s by setting the foreign key explicitly in the code by updating it to null
before deletion of Category
. Is there any way of doing it in use of annotations?
This is the Category
entity:
@Entity
@Table(name = "category")
public class Category implements Serializable {
@OneToMany(mappedBy="category",
targetEntity=Event.class,
fetch=FetchType.LAZY,
cascade= {CascadeType.DETACH, CascadeType.MERGE,
CascadeType.PERSIST, CascadeType.REFRESH})
public Set<Event> getEvents_category() {
return events_category;
}
}
This is the Event
entity:
@Entity
@Table(name = "event")
public class Event implements Serializable {
@ManyToOne(cascade={CascadeType.DETACH, CascadeType.MERGE,
CascadeType.PERSIST, CascadeType.REFRESH})
@JoinColumn(name="events_dancestyle")
public DanceStyle getDanceStyle() {
return danceStyle;
}
}
I've seen that the topic was discussed many times but I haven't seen any solution to that.