【问题标题】:Delete Values from Join Table spring boot从联接表中删除值 spring boot
【发布时间】:2020-03-29 01:08:22
【问题描述】:

我有两张表学生和科目。一个学生可以拥有多个科目,反之亦然。我有两个模型类,并且 vave 在 Spring Boot 和 JPA 中使用多对多关系连接。我的问题是如何从连接表中删除值。但我不知道如何从连接表中删除。对于学生和主题模型,我使用 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> {}

【问题讨论】:

    标签: spring hibernate spring-boot jpa


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      您有两个表 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.
      

      【讨论】:

        猜你喜欢
        • 2021-07-07
        • 2019-10-29
        • 2015-10-25
        • 1970-01-01
        • 1970-01-01
        • 2020-05-21
        • 1970-01-01
        • 2022-10-13
        • 1970-01-01
        相关资源
        最近更新 更多