title: How to implement equals() and hashcode() methods in BaseEntity of JPA?
body: <p>I have a <code>BaseEntity</code> class which is a superclass of all JPA entities in my application.</p>
  
  <pre><code>@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;
  }
  </code></pre>
  
  <p>Every JPA entity extends from <code>BaseEntity</code> and inherit <code>id</code> and <code>version</code> attributes of <code>BaseEntity</code>.</p>
  
  <p>What is the best way here to implement <code>equals()</code> and <code>hashCode()</code> methods in <code>BaseEntity</code>?  Every subclass of <code>BaseEntity</code> will inherit <code>equals()</code> and <code>hashCode()</code> behaviour form <code>BaseEntity</code>.</p>
  
  <p>I want to do something like this:</p>
  
  <pre><code>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;
          }
      }
  </code></pre>
  
  <p>But <code>instanceof</code> operator needs classtype and not class object; that is:</p>
  
  <ul>
  <li><p><code>if(other instanceof BaseEntity)</code></p>
  
  <p>this will work as BaseEntity is classType here</p></li>
  <li><p><code>if(other instanceof this.getClass)</code></p>
  
  <p>this will not work because <code>this.getClass()</code> returns class object of <code>this</code> object</p></li>
  </ul>