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

时间:2010-06-30 07:20:03

标签: java jpa equals hashcode tostring

我有一个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延伸,并继承id的{​​{1}}和version属性。

BaseEntity中实施equals()hashCode()方法的最佳方式是什么? BaseEntity的每个子类都将继承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; } } 运算符需要classtype而不是class对象;那就是:

  • instanceof

    这将起作用,因为BaseEntity是classType

  • if(other instanceof BaseEntity)

    这不起作用,因为if(other instanceof this.getClass)返回this.getClass()对象的类对象

1 个答案:

答案 0 :(得分:2)

你可以做到

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