![](/img/trans.png)
[英]How to implement the equals/hashCode methods for classes that contain double fields
[英]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
和繼承id
和version
的屬性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.