java baseentity_如何在JPA的BaseEntity中实现equals()和hashcode()方法?
我有一個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擴展并繼承BaseEntity的id和version屬性.
在BaseEntity中實現equals()和hashCode()方法的最佳方法是什么? BaseEntity的每個子類都將從BaseEntity繼承equals()和hashCode()行為.
我想做這樣的事情:
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(其他instanceof BaseEntity)
這將起作用,因為BaseEntity在這里是classType
> if(this.getClass的其他實例)
這不起作用,因為this.getClass()返回此對象的類對象
總結
以上是生活随笔為你收集整理的java baseentity_如何在JPA的BaseEntity中实现equals()和hashcode()方法?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 抛出异常 返回值_java通过
- 下一篇: java 软引用_Java中弱引用和软引