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?