如何在JPA的BaseEntity中实现equals()和hashcode()方法? [英] How to implement equals() and hashcode() methods in BaseEntity of JPA?

查看:157
本文介绍了如何在JPA的BaseEntity中实现equals()和hashcode()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 BaseEntity 类,它是应用程序中所有JPA实体的超类。

I have a BaseEntity class which is a superclass of all JPA entities in my application.

@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 属性

Every JPA entity extends from BaseEntity and inherit id and version attributes of BaseEntity.

实现 equals() hashCode()的最佳方法是什么? BaseEntity 中的方法? BaseEntity 的每个子类将继承 equals() hashCode()行为形式 BaseEntity

What is the best way here to implement equals() and hashCode() methods in BaseEntity? Every subclass of BaseEntity will inherit equals() and hashCode() behaviour form 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 运算符需要classtype而不是class对象;即:

But instanceof operator needs classtype and not class object; that is:


  • if(BaseEntity的其他实例)

这将起作用,因为BaseEntity在此处是classType

this will work as BaseEntity is classType here

if(其他实例。 getClass)

这将不起作用,因为 this.getClass()返回类对象对象

this will not work because this.getClass() returns class object of this object

推荐答案

您可以

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

这篇关于如何在JPA的BaseEntity中实现equals()和hashcode()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆