Reputation: 393
I have two tables students and subjects. A student can have more than one subject and vice versa. I have two model classes and vave joined using Many to Many relationship in spring boot and JPA.My problem is how I can delete values from my join table. But I can't figure out how I can do delete from join table. For Student and Subject Model I delete comfortably using deleteById() function.This is my code:
@ManyToMany
@JoinTable(
name = "student_subject",
joinColumns = @JoinColumn(name = "student_id"),
inverseJoinColumns = @JoinColumn(name = "subject_id"))
private Set<SubjectModel> subjects;
//and my repository Class
@Repository
public interface SubjectDao extends JpaRepository<SubjectModel, Integer> {}
Upvotes: 2
Views: 3030
Reputation: 752
You have two table Student and Subject. And I suppose you want is delete one of the subject from a student. For that you should let jpa delete the row from subject and student-subject association table. And dont need to user SubjectRepository. Take a look.
Student firstStudent=studentRepository.findById(1);
Set<SubjectModel> subs=firstStudent.getSubject();
subs.clear();
firstStudent.setSubject(subs);
studentRepository.save(firstStudent); // this method will delete the row from assiciation table as well as the subject table.
Upvotes: 0
Reputation: 34
You have to delete the corresponding objects form both sides of the link, and then save them.
myStudent.getSubjects().remove(mySubject);
mySubject.getStudents().remove(myStudent);
SubjectDao subjectDao = new SubjectDao();
subjectDao.save(mySubject);
Here another examle: Hibernate: delete many-to-many association
Upvotes: 1