我有两个表:学生表和主题表。一个学生可以有多个科目,反之亦然。我有两个模型类,vave在spring boot中使用多对多关系连接,JPA.My问题是如何从连接表中删除值。但是我不知道如何才能从连接表中删除。对于我使用deleteById()轻松删除的学生和科目模型,function.This是我的代码:
@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> {}发布于 2019-12-04 18:08:46
您必须从链接的两端删除相应的对象,然后保存它们。
myStudent.getSubjects().remove(mySubject);
mySubject.getStudents().remove(myStudent);
SubjectDao subjectDao = new SubjectDao();
subjectDao.save(mySubject);发布于 2019-12-04 18:36:53
您有两个表,分别是Student和Subject。我想你想要的是从一个学生身上删除一个主题。为此,您应该让jpa从subject和student-subject关联表中删除行。并且不需要使用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.https://stackoverflow.com/questions/59172489
复制相似问题