Hibernate/Kotlin/Spring - ManyToMany cant delete items

Viewed 57

I have two tables that are linked with @ManyToMany .I want that when deleting items that it deletes only own items and not the connected ones. I have 2 Classes. In Class "A" there is no issue , it deletes only its own items and not the connected one (the ones that represent class B). But when i delete items from class "B" i am getting error that is not possible because of foreign key. I have tried to use CascadeType.REMOVE , which will work but it will also delete the connected items from class "A" which i don't want to.

Class A:


@Entity
@TypeDef(name = "jsonb", typeClass = JsonBinaryType::class)
data class Student (
      .....
        @ManyToMany( fetch = FetchType.LAZY , cascade = [
                CascadeType.PERSIST,
                CascadeType.MERGE
        ])
        @JoinTable(name = "student_teacher",
                joinColumns = [JoinColumn(name = "student_id", referencedColumnName = "id")],
                inverseJoinColumns = [JoinColumn(name = "teacher_id", referencedColumnName = "id")]
        )
        @JsonIgnore
        val teachers: MutableSet<Teacher> ,

)
{
        val teachersList: MutableSet<Teacher>
                get() = teachers

}

Class B:

@Entity
@TypeDef(name = "list-array", typeClass = ListArrayType::class)
data class Teacher(
 .....
){
    @ManyToMany(mappedBy = "teachers",fetch = FetchType.LAZY)
    @JsonIgnore
    val students: MutableSet<Student> = MutableSet<Student>()
}
1 Answers

Got it work this way:

   @Entity
@TypeDef(name = "list-array", typeClass = ListArrayType::class)
data class Teacher(
 .....
){
    @ManyToMany(mappedBy = "teachers",fetch = FetchType.LAZY)
    @JsonIgnore
    val students: MutableSet<Student> = MutableSet<Student>()

  @PreRemove
fun removeTeacher() {
    for (student in students) {
        student.teachersList.remove(this)
    }
}
}
Related