如何在JPA的BaseEntity中实现equals()和hashcode()方法?

9

我有一个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并继承BaseEntityidversion属性。
BaseEntity中实现equals()hashCode()方法的最佳方法是什么?每个BaseEntity的子类都会继承BaseEntityequals()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 对象的类对象


1
只是提醒一下,JPA规范并不要求实体提供特定的hashCode/equals处理方式,而使用DataNucleus作为JPA实现也不需要这种形式的任何东西。显然,其他一些实现(例如Hibernate?)可能会强制执行这一点。 - DataNucleus
@DataNucleus,您能否提供一个参考链接,指出Hibernate在equals()/hashCode()方面并不强制要求(提示:Hibernate本身不会在实体对象上调用equals()hashCode())。 - Pascal Thivent
1个回答

4

您可以做

if (this.getClass().isInstance(other)) {
  // code
}

https://dev59.com/IXI-5IYBdhLWcg3wSGUB - user237673

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接