I learned that in Spring Data JDBC I need to implement many to many relationships by having a reference to the ID of one entity in the other entity:
public class Student {
@Id
private Long studentId;
private String studentName;
@MappedCollection(idColumn = "student_id", keyColumn = "course_id")
private Set<CourseRef> courses;
}
public class Course {
@Id
private Long courseId;
private String courseName;
}
@Table("student_course")
public class CourseRef {
@Id
private Long studentCourseId;
private Long courseId;
@MappedCollection(idColumn = "student_course_id", keyColumn = "test_score_id")
private List<TestScore> testScores;
}
public class TestScore {
@Id
private Long testScoreId;
private Integer value;
}
public interface StudentRepository implements CrudRepository<Student, Long> {
}
public interface CourseRepository implements CrudRepository<Course, Long> {
}
public class StudentRepositoryTest {
@Autowired
StudentRepository repository;
@Test
void testAddTestScore() {
Student student = repository.findById(1L).get();
assertNotNull(student);
Set<CourseRef> courses = student.getCourses();
CourseRef course = courses.stream().filter(c -> c.getCourseId() == 2).findFirst().orElse(null);
assertNotNull(course);
courses.remove(course);
course.addTestScore(TestScore.create(90);
courses.add(course);
students.setCourses(courses);
repository.save(student);
}
}
With this setup I have a student
table, course
table, student_course
table, and test_score
table that has a foreign key to a student_course id. But I'm having trouble adding a new test score. The repository is unable to save the updated student due to a foreign key constraint failure with the student_course_id
column. I was wondering, is it possible to add new test scores with this approach, and if so would I need to create a new repository?