I have to entities modeled Session and Speaker, with ManyToMany relationship, and I wanted to delete an instance of Session, but in the DB it is the foreign key of another table. Below is the entity model
@Entity(name = "sessions")
public class Session {
// attributes do not respect camel case notations because they
// need to match table notations in order to auto bind without annotations
// otherwise that is done with @Column annotation
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long session_id;
private String session_name;
private String session_description;
private String session_length;
@OnDelete(action = OnDeleteAction.CASCADE)
@ManyToMany()
@JoinTable(
name = "session_speakers",
joinColumns = @JoinColumn(name = "session_id"),
inverseJoinColumns = @JoinColumn(name = "speaker_id")
)
private List<Speaker> speakers;
public Session() {
}
I tried to use OnDelete Cascade, but it still didn't work. (I did read that it is not advised to use on ManyToMany relationship)
@RequestMapping(value = "{id}", method = RequestMethod.DELETE)
public void delete(@PathVariable Long id){
sessionRepo.deleteById(id);
}
EDIT:
here is also the Speaker entity
@Entity(name = "speakers")
public class Speaker {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long speaker_id;
private String first_name;
private String last_name;
private String title;
private String company;
private String speaker_bio;
@Lob
@Type(type = "org.hibernate.type.BinaryType")
private Byte[] speaker_photo;
public Byte[] getSpeaker_photo() {
return speaker_photo;
}
public void setSpeaker_photo(Byte[] speaker_photo) {
this.speaker_photo = speaker_photo;
}
@ManyToMany(mappedBy = "speakers")
@JsonIgnore// added to resolve serialization issues
private List<Session> sessions;