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

2024-03-24

我有一个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 and version的属性BaseEntity.

这里最好的实施方式是什么equals() and hashCode()中的方法BaseEntity?的每个子类BaseEntity将继承equals() and 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;
        }
    }

But instanceof运算符需要类类型而不是类对象;那是:

  • if(other instanceof BaseEntity)

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

  • if(other instanceof this.getClass)

    这行不通,因为this.getClass()返回类对象this object


你可以做

if (this.getClass().isInstance(other)) {
  // code
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐