【发布时间】:2011-11-06 02:30:24
【问题描述】:
我正在 Hibernate 中开发一个应用程序,其中有如下模型类:
public class Employee
{
private int ID;
private String name;
private Department department;
//other properties
//constructors, getters and setters
}
请注意,ID 不是用户填充的值,而是使用 GenerationType.Identity 作为strategy 填充的。
另外我还有一个班级Department如下:
public class Department
{
private int ID;
private String name;
private Set<Employee> employees; //this is actually a HashSet
//other implementations
}
Employee 和Department 之间存在ManyToOne 双向关系。
所以要将新的Employee 添加到现有的Department,我执行以下操作
Department existingDepartment = ...;
Employee newEmployee = ...;
existingDepartment.addEmployee(newEmployee);
employee.setDepartent(existinDepartment);
session.save(newEmployee);
现在,如果两个 Employee 对象具有相同的 ID,则它们在概念上是相同的。所以我在Employee 类中的equals() 方法如下所示:
public boolean equals(Object o)
{
if(!(o instanceOf Employee))
{
return false;
}
Employee other = (Employee)o;
if(this.ID == o.etID())
{
return true;
}
return false;
}
现在的问题是当我创建一个new Employee(); 时,我没有它的ID,因为它会在持久化时被分配。所以当我说
existingDepartment.addEmployee(newEmployee);
Department 对象的内部HashSet 有效地使用了一个被破坏的equals() 方法[因为它使用成员变量来确定未正确初始化的相等性]。
这似乎是一个非常基本的问题,但是,我该如何解决呢?还是我设计的课程完全错误?还是应该重写我的equals 方法来比较其他值而不是ID,我猜这很荒谬。
【问题讨论】: