Search code examples
javahibernatenullpointerexceptionassociate

OneToMany association collection is null in Hibernate application


I am developing a simple Hibernate application to test an OneToMany association. The Entities I use are Employee and Department which has many 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

}

I create some records with:

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);

However in the last line: emps.remove(emp2); I receive a NullPointerException, the emps Collection is namely null. I have tried to change the owner of the association with:

 @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

    }

However the result the same. Why is the Set of Employees not created. What must be changed in order to make it work?


Solution

  • Initialize the collection yourself, either in the constructor or by specifying an initial value for the field.

    Indeed Hibernate will initialize the collection to an empty collection when you fetch the object from the database. However, when you create the object yourself and persist it, Hibernate will not really touch the object you created, only persist it, so it won't initialize the field for you in that case.

    If you want to make sure the field is never null, which I agree is desirable, simply make sure of it yourself, even before persisting.