从Join Table Spring Boot中删除值

时间:2019-12-04 09:14:55

标签: spring hibernate spring-boot jpa

我有两个表的学生和科目。一个学生可以有多个科目,反之亦然。我有两个模型类,并且在Spring Boot和JPA中使用多对多关系进行vave连接。我的问题是如何从连接表中删除值。但是我不知道如何从联接表中删除。对于学生模型和学科模型,我可以使用deleteById()函数轻松删除。这是我的代码:

          @ManyToMany
          @JoinTable(
          name = "student_subject", 
          joinColumns = @JoinColumn(name = "student_id"), 
          inverseJoinColumns = @JoinColumn(name = "subject_id"))
          private Set<SubjectModel> subjects;

//和我的存储库类

          @Repository
          public interface SubjectDao extends JpaRepository<SubjectModel, Integer> {}

2 个答案:

答案 0 :(得分:0)

您必须删除链接两侧的相应对象,然后保存它们。

myStudent.getSubjects().remove(mySubject);
mySubject.getStudents().remove(myStudent);
SubjectDao subjectDao = new SubjectDao();
subjectDao.save(mySubject);

这里还有另一个例子:Hibernate: delete many-to-many association

答案 1 :(得分:0)

您有两个表Student和Subject。 我想您想从学生中删除其中一个主题。 为此,您应该让jpa从学科和学生-学科关联表中删除该行。并且不需要用户SubjectRepository。 看看。

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.