Inserting data in a ManyToMany relationship

Viewed 48

I have two classes with ManyToMany relationship.

Student.java

@Entity
public class Student {
    @Id
    private Long id;
    private String name;

    @ManyToMany(cascade = {CascadeType.ALL})
    @JoinTable(name = "student_class", joinColumns = {@JoinColumn(name = "student_id")},
                                        inverseJoinColumns = {@JoinColumn(name = "class_id")})
    private List<Class> classList = new ArrayList<>();
}

Class.java

@Entity
public class Class {
    @Id
    @GeneratedValue
    private Long id;
    private String name;

    @ManyToMany(mappedBy = "classList",cascade = {CascadeType.ALL})
    private List<Student> students;
}

My question is how to implement a POST request in the controller? Do I add class to classList for a student and the student will automatically get inserted into students list?

1 Answers

The class that will actually be monitored by JPA for references is the one pointed with mappedBy .

This means that JPA during a save or update or delete will consider the mappings that the Student holds on classList. Therefore the cascade you have written here has no point.

    @ManyToMany(mappedBy = "classList",cascade = {CascadeType.ALL})
    private List<Student> students;

The only cascade that will actualy work is the one pointed with mappedBy

 @ManyToMany(cascade = {CascadeType.ALL})
    @JoinTable(name = "student_class", joinColumns = {@JoinColumn(name = "student_id")},
                                        inverseJoinColumns = {@JoinColumn(name = "class_id")})
    private List<Class> classList = new ArrayList<>();

So to your question

Do I add class to classList for a student and the student will automatically get inserted into students list?

Yes it will be added to the list so you can see it, but it will not consider any changes that you make to that studentList. So if you make modifications directly on studentList then those modifications will not be persisted in your database.

Related