【发布时间】:2015-02-01 21:47:14
【问题描述】:
首先,考虑sn-p,
public class Employee
{
private Integer id;
private String firstname;
private String lastName;
private String department;
// public getters and setters here, i said PUBLIC
}
我创建了 2 个具有相同 id 的对象,并且所有字段的其余部分也相同。
Employee e1 = new Employee();
Employee e2 = new Employee();
e1.setId(100);
e2.setId(100);
//Prints false in console
System.out.println(e1.equals(e2));
整个问题从这里开始 在实时应用程序中,这必须返回 true。
因此,每个人都知道存在解决方案(实现 equals() 和 hashcode())
public boolean equals(Object o) {
if(o == null)
{
return false;
}
if (o == this)
{
return true;
}
if (getClass() != o.getClass())
{
return false;
}
Employee e = (Employee) o;
return (this.getId() == e.getId());
}
@Override
public int hashCode()
{
final int PRIME = 31;
int result = 1;
result = PRIME * result + getId();
return result;
}
现在,像往常一样:
Employee e1 = new Employee();
Employee e2 = new Employee();
e1.setId(100);
e2.setId(100);
//Prints 'true' now
System.out.println(e1.equals(e2));
Set<Employee> employees = new HashSet<Employee>();
employees.add(e1);
employees.add(e2);
//Prints ofcourse one objects(which was a requirement)
System.out.println(employees);
我正在阅读这篇出色的文章Don't Let Hibernate Steal Your Identity。但有一件事我没有完全理解。上面讨论的整个问题及其解决方案以及链接的文章正在处理 2 个 Employee 对象 ID 相同时的问题。
考虑一下,当我们有一个 id 字段 的 private setter 时,id 字段由 generator 类生成 在 hbm.xml 中提供。一旦我开始持久化 Employee 对象(我将无法更改 id),我发现不需要实现 equals 和 hashcode 方法。我确信我遗漏了一些东西,因为我的直觉告诉我们,当一个特定的概念在网络上旋转太多时,为了避免一些常见的错误,它一定总是摆在你面前?当我有一个用于 id 字段的私有设置器时,我还需要实现这两种方法吗?
【问题讨论】:
标签: java hibernate jpa equals hashcode