So I got two entities, Student
and Course
. One Student
can have many Course
and one Course
can have many Student
. Normally, I would have Hibernate generate a jointable like this:
@ManyToMany
@JoinTable(
name="studentCourseJoinTable",
joinColumns= {
@JoinColumn(
name="studentId",
referencedColumnName="studentId"
) },
inverseJoinColumns= {
@JoinColumn(
name="courseId",
referencedColumnName="courseId")
}
)
private List<Course> courses = new ArrayList<Course>();
Problem is, that I need to store the grade of the student in this course. For the sake of simplicity, lets say it is just a normal integer value. Without Hibernate, I'd build a simple jointable with a extra column for the grade value, something like this:
+-----------+----------+-------+
| studentId | courseId | grade |
+-----------+----------+-------+
| 1 | 1 | 1 |
| 1 | 2 | 2 |
| 2 | 1 | 5 |
| 2 | 3 | 6 |
+-----------+----------+-------+
So I followed this guide in the JPA Wikibook and set it up like this:
@Entity
public class Student implements Serializable
{
...
@OneToMany(mappedBy="student")
private List<StudentCourse> courses = new ArrayList<StudentCourse>();
...
}
@Entity
public class Course implements Serializable
{
...
@OneToMany(mappedBy="course")
private List<StudentCourse> courses = new ArrayList<StudentCourse>();
...
}
@Entity
@IdClass(StudentCourse.class)
public class StudentCourse implements Serializable
{
@Id
private int studentId;
@Id
private int courseId;
private int grade;
@ManyToOne
@PrimaryKeyJoinColumn(name="studentId", referencedColumnName="studentId")
private Student student;
@ManyToOne
@PrimaryKeyJoinColumn(name="courseId", referencedColumnName="courseId")
private Course course;
...
}
It is ugly, but it works how it should work.
Now, the problem: Cascading. It's no problem with the @ManyToMany
relation in the first example (I got another relation within Student
, but it doesn't matter for this problem).
What I want is that if I delete a Student
, the corresponding rows in the StudentCourse
table gets also dropped, and the other way around: If I delete a Course
, the corresponding rows should also get dropped. But I don't get
- where to put the
cascade = CascadeType.XY
- which type of the cascade
I tried to use cascade = CascadeType.MERGE
on both the Student
and the Course
, but this just leads to this if I delete a Student:
2022-02-09T22:33:59.222+0100 ERROR integrity constraint violation: foreign key no action; FKD0KC5NKFVH9A0DIFGUI129HFC table: STUDENTCOURSES