cascade.Persist in @ManyToMany how does it work generally and how does it work in this situation

42 Views Asked by At

I have 2 entities, one is Student and the other is Course. They are connected to each other in a manytomany bidirectional manner. I am performing an operation as seen in the code below.

@NoArgsConstructor
@AllArgsConstructor
@Entity
@SuperBuilder
@Table(name = "_student")
@DiscriminatorValue("ent_Student")
public class Student extends User{
    
      @JsonIgnore   
      @ManyToMany(cascade = {
                CascadeType.PERSIST,
                CascadeType.MERGE
            })
            @JoinTable(name = "students_courses",
                joinColumns = @JoinColumn(name = "student_id"),
                inverseJoinColumns = @JoinColumn(name = "course_id")
      )
      private Set<Course> courses;

      
      
    public Set<Course> getCourses() {
        if(courses == null) {
            courses = new HashSet<Course>();
        }
        return courses;
    }

    public void setCourses(Set<Course> courses) {
        this.courses = courses;
    }
      
      



}
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "_course")
public class Course {
    
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      public Integer id;

      @Column(unique = true)
      public String courseName;
      
      @JsonIgnore
      @ManyToMany(mappedBy = "courses")
      public Set<Student> students;

//getter setters
}

and i have @Service method like this

    public AssignCourseToStudentResponse assignCourseToStudent2(Integer id,Integer id2) {
        
        AssignCourseToStudentResponse resp;
        
        Optional<Student> st = student_Repo.findById(id);
        
        Optional<Course> course = course_repo.findById(id2);
    
        Student s = st.orElseThrow();
        
        s.getCourses().add(course.get());
        
        student_Repo.save(st.get());
        
        Optional<Course> courseDebug = course_repo.findById(id2);
        
        Iterator<Student> it= courseDebug.get().students.iterator();
        
        while(it.hasNext()) {
            System.out.println(it.next());
            if(it.hasNext() == false) {
                break;
            }
        }
        
        resp = AssignCourseToStudentResponse.builder().message(ResponseMessage.SUCCESSFUL).build();
        
        return resp;
    } 

when i execute the code written in the service section above

it is added to table as i expected.

But my real question is, if I delete cascade.persist from student, it adds student and course to the intermediate table just as before and creates a relationship between them.

So, what is the purpose of persist in this case, what does hibernate do in the background? Another question I have is that I just added a course to the student object and when I save the student directly, I can access my student object from the course entity, When I save only for the student object, how was my student added to the Student collection in the course object? Isn't this a cascade situation? Or how does hibernate work in this case? I'm trying to learn software. Could you please explain it in a little more detail. Thank you

I wasn't expecting data to be added to the intermediate table when cascade.persist was not present

0

There are 0 best solutions below