Let's take a close look at your code:
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();
You have created Department
, three Employees
, set reference to that Department
for each Employee
and persisted them.
Set emps
will be null because after you persisted employees to database, you didn't reload department
. If you change code like this:
....
session.persist(emp3);
department = session.get(Department.class, department.getDepartmentId());
Set<Employee> emps = department.getEmployees();
emps.remove(emp2);
You should be fine.
Another point I'd like to mention - your relation between Department
and Employees
are mappedBy
Department
, which literally means that Department
is let's say "master" entity and its Employee
are "slave", or, if you prefer, Department
takes all responsibilities on maintaining mapping and references. But, in your code I commented above, you put this mapping responsibility on Employee
entities. You may want to change your code that way:
department.add(emp1);
department.add(emp2);
department.add(emp2);
session.persist(department);
in order to make Department
do its job of maintaining mapping and references.