JPA:OneToMany关系使Collection为空

时间:2019-01-01 21:55:26

标签: java spring-boot spring-data-jpa

似乎我在理解JPA以及OneToMany关系如何实际工作方面遇到了困难。

例如,假设我有一个对象Class

@Entity
public class Class {
    @Id
    private String className;

    @OneToMany(cascade = Cascade.ALL, orphanRemoval = true)
    private Set<Student> students;

    // Constructors, Getters, Setter
}

我还有一个对象Student,其中保存着类。

@Entity
public class Student {
    @Id
    private String studentName;

    @ManyToOne
    private Class class;

    // Constructors, Getters, Setter
}

很明显,一个学生可以上多个课,但忘了。

为什么当我建立一个班级,然后使用该班级建立一对学生时,findAll()上的ClassRepository却给我空了一组学生。

Class class = new Class("CS", new HashSet<>());
classRepository.save(class); // repository has no special functions

Student student1 = new Student("1", class);
Student student2 = new Student("2", class);

studentRepository.save(student1);
studentRepository.save(student2);

classRepository.findAll() // Returns me a List<Class> with only one class object that has an empty set.

我当时认为上面的代码应该自动看到两个学生来自同一班,因此当我调用buildingRepository.findAll()时,它将返回一个Class对象,并正确填充了这些学生。< / p>

那我的理解错了吗?还是我的代码错了?我该如何修改它以解决问题?

1 个答案:

答案 0 :(得分:1)

您可以选择:

1。单向terraform apply

@OneToMany

现在,如果我们坚持一个@Entity public class Class { @Id private String className; @OneToMany(cascade = Cascade.ALL, orphanRemoval = true) private List<Student> students=new ArrayList<>(); // Constructors, Getters, Setter } @Entity public class Student { @Id private String studentName; // Constructors, Getters, Setter }

Class

2。具有Class class1=new Class("name1"); class1.getStudents().add(new Student("student1Name")); // then you can make a save of class1 in db classRepository.save(class); 的单向@OneToMany

要解决上述额外的联接表问题,我们只需要在组合中添加@JoinColumn

@JoinColumn

3。双向@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name = "class_id") private List<Student> students = new ArrayList<>();

映射@OneToMany关联关系的最佳方法是依靠@ManyToOne端传播所有实体状态更改:

@OneToMany

要坚持下去:

@Entity
public class Class {
    @Id
    private String className;

    @OneToMany(
        mappedBy = "class",
        cascade = CascadeType.ALL,
        orphanRemoval = true
    )
    private List<Student> students=new ArrayList<>();

    // Constructors, Getters, Setter
    public void addStudent(Student student) {
        students.add(student);
        student.setClass(this);
    }

    public void removeStudent(Student student) {
        students.remove(student);
        student.setClass(null);
    }
}


@Entity
public class Student {
    @Id
    private String studentName;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "class_id")
    private Class class;

}