JPA delete an entry from list in Many-To-Many relationship

Viewed 35

Those are my classes. I want to delete items from likedCourses. So I expect JPA to delete item from course_like table. I looked and try to understand from other examples but couldn't. It is like deletion doesn't exist in JPA realm when there is relation. It is good for selecting though. I'd want to share what I tried but I couldn't find anything about it.

Note : I see that in ManyToMany relationship there is not orphanRemoval option.

@Entity
class Student {

    @Id
    Long id;

    @ManyToMany
    @JoinTable(
    name = "course_like", 
    joinColumns = @JoinColumn(name = "student_id"), 
    inverseJoinColumns = @JoinColumn(name = "course_id"))
    Set<Course> likedCourses
}


@Entity
class Course {

    @Id
    Long id;

   
    @ManyToMany(mappedBy = "likedCourses")
    Set<Student> likes;
}
1 Answers

If you want to remove an entry from the course_like table, you will have to load the Student and remove the element from the likedCourses set that should be removed. If you do that in a @Transactional method, you will see that Hibernate will emit delete statements to delete the rows that represent the removed objects from the likedCourses set. That's the magic of an ORM, it synchronizes the object graph with the database, without you telling it to emit statement A, B, ...

Related