【问题标题】:How to implement equals() and hashcode() methods in BaseEntity of JPA?如何在 JPA 的 BaseEntity 中实现 equals() 和 hashcode() 方法?
【发布时间】:2011-03-09 23:55:54
【问题描述】:

我有一个 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 的每个子类都将继承 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;
        }
    }

但是instanceof 操作符需要类类型而不是类对象;那就是:

  • if(other instanceof BaseEntity)

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

  • if(other instanceof this.getClass)

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

【问题讨论】:

  • 请注意,JPA 规范不要求实体为 hashCode/equals 提供特定处理,并且使用 DataNucleus 作为 JPA 实现不需要任何这种形式。显然,其他一些人(例如 Hibernate?)可能会将其强加给您
  • @DataNucleus 您能否提供一个参考,指出 Hibernate 确实对您施加了任何与 equals()/hashCode() 相关的事情(提示:Hibernate 本身确实调用 equals() 和 @987654342 @ 在实体对象上)。

标签: java jpa equals hashcode tostring


【解决方案1】:

你可以的

if (this.getClass().isInstance(other)) {
  // code
}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-10
  • 2011-05-22
  • 2019-06-02
  • 1970-01-01
  • 2020-02-21
  • 1970-01-01
相关资源
最近更新 更多