JPA一对多的关系

时间:2015-08-03 20:23:18

标签: java-ee jpa eclipselink

我的网络应用中有简单的OneToMany关系。我使用EclipseLink 2.5.1和PostgreSQL。我的交易由glassfish 4.1管理。

public class Student

...

@ManyToOne
@JoinColumn(name = "school_id")
private School school;

SA

public class School

...

@OneToMany(mappedBy = "school", cascade = CascadeType.ALL)
private List<Student> students;

保存操作:

public void process( {
    School school = baseManager.findSchoolById(1);
    Student student = new Student();
    student.setSchool(school);
    baseManager.createStudent(student);

    //to check operation result
    School school = baseManager.findSchoolById(1);  //school does not own previously saved student, why?
)

baseManager是一个EJB无状态bean。 findSchoolById(int id)通过琐碎的NamedQuery找到上学。 createStudent(Student s)只有persist新生。即使我刷新了我的页面,我也没有{!1}}的学生。 id = 1位于CDI baseManager bean中。学生正确保存到数据库。当我重新部署我的应用程序时,以前保存的数据已正确加载到我的应用程序。我做错了什么?

2 个答案:

答案 0 :(得分:1)

您可能需要设置关系的两个方面。因此,您需要将学生添加到学校。

    public void process( {
        School school = baseManager.findSchoolById(1);
        Student student = new Student();
        student.setSchool(school);
        school.addStudent(student);  //  <---- add the student to the List held by the school.
        baseManager.createStudent(student);

        School school = baseManager.findSchoolById(1);
)

答案 1 :(得分:0)

可能只是一个错字 - 但要查看结果,processSchool school = baseManager.findeSchoolById(1);中的最后一行显然应该返回与方法第一行内相同的结果。

您是否使用List<Student> studentsOfSchool = baseManager.findeStudentsBySchool(1);

等检查结果
相关问题