I have 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 euqals() 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