【发布时间】:2011-03-09 23:55:54
【问题描述】:
我有一个 BaseEntity 类,它是我的应用程序中所有 JPA 实体的超类。
@MappedSuperclass
public abstract class BaseEntity implements Serializable {
private static final long serialVersionUID = -3307436748176180347L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID", nullable=false, updatable=false)
protected long id;
@Version
@Column(name="VERSION", nullable=false, updatable=false, unique=false)
protected long version;
}
每个 JPA 实体都从 BaseEntity 扩展而来,并继承 BaseEntity 的 id 和 version 属性。
在BaseEntity 中实现equals() 和hashCode() 方法的最佳方式是什么? BaseEntity 的每个子类都将继承 equals() 和 hashCode() 行为形式 BaseEntity。
我想做这样的事情:
public boolean equals(Object other){
if (other instanceof this.getClass()){ //this.getClass() gives class object but instanceof operator expect ClassType; so it does not work
return this.id == ((BaseEntity)other).id;
} else {
return false;
}
}
但是instanceof 操作符需要类类型而不是类对象;那就是:
-
if(other instanceof BaseEntity)这将起作用,因为 BaseEntity 在这里是 classType
-
if(other instanceof this.getClass)这不起作用,因为
this.getClass()返回this对象的类对象
【问题讨论】:
-
请注意,JPA 规范不要求实体为 hashCode/equals 提供特定处理,并且使用 DataNucleus 作为 JPA 实现不需要任何这种形式。显然,其他一些人(例如 Hibernate?)可能会将其强加给您
-
@DataNucleus 您能否提供一个参考,指出 Hibernate 确实对您施加了任何与
equals()/hashCode()相关的事情(提示:Hibernate 本身确实不调用equals()和 @987654342 @ 在实体对象上)。
标签: java jpa equals hashcode tostring