How to implement equals() and hashcode() methods in BaseEntity of JPA?

橙三吉。 提交于 2019-12-10 14:16:41

问题


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 of this 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!