I am developing an application in Hibernate where I have model classes like these:
public class Employee { private int ID; private String name; private Department department;
Note that the ID not a value populated by the user, and is populated using GenerationType.Identity as a strategy .
I also have another Department class as follows:
public class Department { private int ID; private String name; private Set<Employee> employees;
There is a bi-directional ManyToOne relationship between Employee and a Department .
So, to add a new Employee to an existing Department , I do the following
Department existingDepartment = ...; Employee newEmployee = ...; existingDepartment.addEmployee(newEmployee); employee.setDepartent(existinDepartment); session.save(newEmployee);
Now, conceptually, two Employee objects are the same if they have the same ID . Therefore, my equals() method in the Employee class looks like this:
public boolean equals(Object o) { if(!(o instanceOf Employee)) { return false; } Employee other = (Employee)o; if(this.ID == o.etID()) { return true; } return false; }
Now the problem is that I create new Employee(); I do not have its ID , since it will be assigned when it is saved. Therefore when i say
existingDepartment.addEmployee(newEmployee);
The Department internal HashSet effectively uses the equals() method, which is broken [because it uses a member variable to determine an equality that was not correctly initialized).
This seems like a very simple problem, but how can I solve it? Or am I designing my classes incorrectly? Or whether my equals method should be rewritten to compare other values instead of ID , which, I think, would be absurd.