Reputation: 326
I have the following classes:
@Entity
@Table(name = "lecture")
public class Lecture {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(nullable = false)
private String name;
@OneToOne
@JoinColumn(nullable = false, name = "professorId")
@JsonIgnore
private Professor professor;
}
And:
@Entity
@IdClass(ListenTo.class)
@Table(name = "listen_to")
public class ListenTo implements Serializable {
@Id
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
@JoinColumn(nullable = false, name = "lectureId")
private Lecture lecture;
@Id
@ManyToOne(cascade = CascadeType.REMOVE)
@JoinColumn(nullable = false, name = "studentId")
private Student student;
}
And I want to delete a lecture through this function:
public void delete(Lecture lecture) {
currentSession().delete(lecture);
}
I created the table like this:
create table lecture (
id bigint primary key not null auto_increment,
name varchar(500) not null,
professorId bigint not null,
foreign key (professorId) references professorId (id)
);
create table listen_to (
lectureId BIGINT not null references lecture(id),
studentId BIGINT not null references student(id),
primary key(lectureId,studentId)
);
However, I keep getting this error:
Causing: java.sql.SQLIntegrityConstraintViolationException: (conn=10) Cannot delete or update a parent row: a foreign key constraint fails (`myDBS`.`listen_to`, CONSTRAINT `listen_to_ibfk_1` FOREIGN KEY (`lectureId`) REFERENCES `lecture` (`id`))
I tried multiple things, including using this function to delete:
public boolean deleteById(Class<?> type, Serializable id) {
Object persistentInstance = currentSession().load(type, id);
if (persistentInstance != null) {
currentSession().delete(persistentInstance);
return true;
}
return false;
}
but it still doesn't work..
Upvotes: 0
Views: 557
Reputation: 16400
You first have to delete all ListenTo
entries that refer to this lecture before you can delete the lecture. Use delete from ListenTo l where l.lecture.id = :id
and bind the lecture id, before you delete the lecture itself.
Upvotes: 1