title: What is the correct way of overriding hashCode () and equals () methods of persistent entity?
body: <p>I have a simple class Role:</p>
  
  <pre><code>@Entity
  @Table (name = "ROLE")
  public class Role implements Serializable {
  
      @Id
      @GeneratedValue
      private Integer id;
      @Column
      private String roleName;
  
      public Role () { }
  
      public Role (String roleName) {
          this.roleName = roleName;
      }
  
      public void setId (Integer id) {
          this.id = id;
      }
  
      public Integer getId () {
          return id;
      }
  
      public void setRoleName (String roleName) {
          this.roleName = roleName;
      }
  
      public String getRoleName () {
          return roleName;
      }
  }
  </code></pre>
  
  <p>Now I want to override its methods equals and hashCode. My first suggestion is:</p>
  
  <pre><code>public boolean equals (Object obj) {
      if (obj instanceof Role) {
          return ((Role)obj).getRoleName ().equals (roleName);
      }
      return false;
  }
  
  public int hashCode () {
      return id; 
  }
  </code></pre>
  
  <p>But when I create new Role object, its id is null. That's why I have some problem with hashCode method implementation. Now I can simply return <code>roleName.hashCode ()</code> but what if roleName is not necessary field? I'm almost sure that it's not so difficult to make up more complicated example which can't be solved by returning hashCode of one of its fields. </p>
  
  <p>So I'd like to see some links to related discussions or to hear your experience of solving this problem. Thanks!</p>