在Hibernate应用程序中,OneToMany关联集合为null

时间:2014-04-27 13:14:46

标签: java hibernate nullpointerexception associate

我正在开发一个简单的Hibernate应用程序来测试OneToMany关联。我使用的实体是EmployeeDepartment,其中包含许多Employees

@Entity
public class Department {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long departmentId;

    @OneToMany(cascade=CascadeType.ALL, fetch = FetchType.EAGER, mappedBy="department")
    private Set<Employee> employees;

...
getters/setters

}

@Entity
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long employeeId;

    @ManyToOne
    @JoinColumn(name="employee_fk")
    private Department department;

...
getters/setters

}

我创建了一些记录:

tx.begin();

        Department department = new Department();
        department.setDepartmentName("Sales");
        session.persist(department);

        Employee emp1 = new Employee("Ar", "Mu", "111");
        Employee emp2 = new Employee("Tony", "Almeida", "222");
        Employee emp3 = new Employee("Va", "Ka", "333");

        emp1.setDepartment(department);
        emp2.setDepartment(department);
        emp3.setDepartment(department);


        session.persist(emp1);
        session.persist(emp2);
        session.persist(emp3);

        Set<Employee> emps = department.getEmployees();
        emps.remove(emp2);

但是在最后一行:emps.remove(emp2);我收到NullPointerExceptionemps收集即null。我试图通过以下方式更改关联的所有者:

 @Entity
    public class Department {

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long departmentId;

        @OneToMany(cascade=CascadeType.ALL, fetch = FetchType.EAGER)
        @JoinColumn(name="department_fk")
        private Set<Employee> employees;

    ...
    getters/setters

    }

    @Entity
    public class Employee {

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long employeeId;

        @ManyToOne
        @JoinColumn(name="department_fk", insertable=false, updatable=false)
        private Department department;

    ...
    getters/setters

    }
然而结果却一样。为什么Set的{​​{1}}未创建。必须改变什么才能使其发挥作用?

1 个答案:

答案 0 :(得分:0)

自己初始化集合,可以在构造函数中,也可以通过为字段指定初始值。

实际上,当您从数据库中获取对象时,Hibernate会将集合初始化为空集合。但是,当你自己创建对象并坚持下去时,Hibernate不会真正触及你创建的对象,只会坚持它,所以在这种情况下它不会为你初始化字段。

如果你想确保该字段永远不为空,我认为这是可取的,只需自己确认,即使在坚持之前。