У меня есть класс 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.
Как лучше всего реализовать методы equals() и hashCode() в BaseEntity? Каждый подкласс 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, а не объект класса; то есть:
-
if(other instanceof BaseEntity)это будет работать как BaseEntity здесь classType
-
if(other instanceof this.getClass)это не будет работать, потому что
this.getClass()возвращает объект класса объектаthis