2

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> {}

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.