I use Spring Data, JPA, Hibernate and MySQL. I have one to many relation between Event and Category. Obviously one event can have only one category and one category can be assigned many Events. 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 Events 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 my Category:
@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;
}
}
And the Event class:
@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.
Unfortunately it is not currently possible to do this using JPA/Hibernate annotations. See these related questions:
Have JPA/Hibernate to replicate the "ON DELETE SET NULL" functionality
On delete set null in hibernate in @OneToMany
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With