我有一个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
的子类都会继承BaseEntity
的equals()
和hashCode()
行为。我想做如下操作:
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
if(other instanceof this.getClass)
这不会起作用,因为
this.getClass()
返回的是this
对象的类对象
equals()/hashCode()
方面并不强制要求(提示:Hibernate本身不会在实体对象上调用equals()
和hashCode()
)。 - Pascal Thivent