Answer the question
In order to leave comments, you need to log in
By what principle does Spring DataJPA update records in related tables?
There are two entities with a ManyToMany relationship: Student and Course . A student can have several courses, and one course can be taken by several students. I display this relationship in the following table:
CREATE TABLE student_courses
(
student_id INTEGER NOT NULL,
course_id INTEGER NOT NULL,
CONSTRAINT student_course_idx UNIQUE (student_id, course_id),
FOREIGN KEY (student_id) REFERENCES students (id) ON DELETE CASCADE,
FOREIGN KEY (course_id) REFERENCES courses (id) ON DELETE CASCADE
);
@Entity
@Table(name = "students")
public class Student {
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "students_courses",
joinColumns = @JoinColumn(name = "student_id"),
inverseJoinColumns = @JoinColumn(name = "course_id")
)
List<Course> courses;
// другие поля
}
@Entity
@Table(name = "courses")
public class Course {
@ManyToMany(mappedBy = "courses", fetch = FetchType.LAZY)
List<Student> students;
// другие поля
}
@Transactional(readOnly = true)
public interface CrudCourseRepository extends JpaRepository<Course, Integer> {
}
List<Course> courses
. As far as I understand, if I try to update the Student entity by passing it to a CrudStudentRepository#save()
student with an empty list of courses, then all records in the student_courses table that appear in the updated student will be deleted, but in reality this does not happen. By what principle does JpaRepository remove or update links in the link table, student_courses in this case? Why do I update the student record with a Student entity with an empty list of courses, but the student's course association records are not removed from student_courses ?
Answer the question
In order to leave comments, you need to log in
Hello colleague!
Let me add a little bit to your code and note the following:
CrudCourseRepository
How does JpaRepository update relationships in the student_courses table?
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
As far as I understand, if I try to update the Student entity by passing a student with an empty list of courses to the CrudStudentRepository#save(), then all records in the student_courses table that appear in the updated student will be deleted, but in my experience this does not happen. How can I delete/update these records then?
CascadeType.All
either PERSIST & MERGE Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question