如何在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
运算符需要类类型而不是类对象;即:
if(BaseEntity 的其他实例)
这将起作用,因为 BaseEntity 在这里是 classType
if(other instanceof this.getClass)
这将不起作用,因为
this.getClass()
返回this
对象的类对象
I have a BaseEntity
class which is a superclass of all JPA entities in my application.
@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;
}
Every JPA entity extends from BaseEntity
and inherit id
and version
attributes of BaseEntity
.
What is the best way here to implement equals()
and hashCode()
methods in BaseEntity
? Every subclass of BaseEntity
will inherit equals()
and hashCode()
behaviour form BaseEntity
.
I want to do something like this:
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
operator needs classtype and not class object; that is:
if(other instanceof BaseEntity)
this will work as BaseEntity is classType here
if(other instanceof this.getClass)
this will not work because
this.getClass()
returns class object ofthis
object
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你可以做
You can do