E
E
Eugenue Cesarevich2021-01-14 21:40:25
Java
Eugenue Cesarevich, 2021-01-14 21:40:25

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 Student:

@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;
    // другие поля
}


Essence Course:

@Entity
@Table(name = "courses")
public class Course {
    @ManyToMany(mappedBy = "courses", fetch = FetchType.LAZY)
    List<Student> students;
    // другие поля
}


I am working with a database through Spring DataJpa. That is, I use JpaRepository, which accepts entities and automatically updates / deletes / saves. For example, here is the repository for the course (same for the student, only called CrudStudentRepository) :

@Transactional(readOnly = true)
public interface CrudCourseRepository extends JpaRepository<Course, Integer> {
}


Question.

How does JpaRepository update relationships in the student_courses table? The Student entity has a field 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

1 answer(s)
O
Orkhan, 2021-01-15
Hasanly @azerphoenix

Hello colleague!
Let me add a little bit to your code and note the following:

CrudCourseRepository

Probably, it is not necessary to indicate Crud in the name, since other methods may be added to the repository in the future and, accordingly, from the point of view of clean code, the name will not be correct.
How does JpaRepository update relationships in the student_courses table?

As the saying goes, it's better to see once than hear a hundred times. So it's better to include in properties
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

I will assume that you will see something like this:
A SELECT query (selection) from two tables along with a JOIN, and then a query to insert a new record (INSERT)
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?

Here, perhaps, you should pay attention to CascadeType.
For example, if in the OneToMany relationship you try to save the list from the side of the entity itself, then the elements of the list will be saved, but their id will be null, since the entity itself has not yet been saved and has not been assigned an identifier. To avoid this, you can optionally specify CascadeType.Alleither PERSIST & MERGE
In the case of ManyToMany, I think it would be correct to specify the type of cascade. For example, CascadeType.PERSIST CascadeType.MERGE
By the way, there is a good source from which I also draw information from time to time. Here is the link - link
You can have a look.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question