簡體   English   中英

如何在JPA的BaseEntity中實現equals()和hashcode()方法?

[英]How to implement equals() and hashcode() methods in BaseEntity of JPA?

我有一個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和繼承idversion的屬性BaseEntity

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運算符需要classtype而不是class對象; 那是:

  • if(other instanceof BaseEntity)

    這將起作用,因為BaseEntity在這里是classType

  • if(other instanceof this.getClass)

    這不起作用,因為this.getClass()返回this對象的類對象

你可以做

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM