问题
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
回答1:
You can do
if (this.getClass().isInstance(other)) {
// code
}
来源:https://stackoverflow.com/questions/3147166/how-to-implement-equals-and-hashcode-methods-in-baseentity-of-jpa