What is the correct way of overriding hashCode () and equals () methods of persistent entity?

后端 未结 7 2056
青春惊慌失措
青春惊慌失措 2020-12-14 10:28

I have a simple class Role:

@Entity
@Table (name = \"ROLE\")
public class Role implements Serializable {

    @Id
    @GeneratedValue
    private Integer id;         


        
7条回答
  •  执笔经年
    2020-12-14 10:38

    Please find below simple instructions how to create hashCode, equals and toString methods using Apache commons builders.

    hashCode

    1. If two objects are equal according to the equals() method, they must have the same hashCode() value
    2. It is possible that two distinct objects could have the same hashCode().
    3. Please use unique Business ID for the hashCode creation (it is mean that you should use some unique property that represent business entity, for example, name)
    4. Hibernate Entity: please do NOT use Hibernate id for the hashCode creation
    5. You may call for .appendSuper(super.hashCode()) in case your class is subclass

      @Override
      public int hashCode() {
          return new HashCodeBuilder()
                  .append(getName())
                  .toHashCode();
      }
      

    equals

    1. Please compare Business ID (it is mean that you should use some unique property that represent business entity, for example, name)
    2. Hibernate Entity: please do NOT compare Hibernate id
    3. Hibernate Entity: use getters when you access the other object field to let to Hibernate to load the property
    4. You may call for .appendSuper(super.equals(other)) in case your class is subclass

      @Override
      public boolean equals(final Object other) {
          if (this == other)
              return true;
          if (!(other instanceof TreeNode))
              return false;
          TreeNode castOther = (TreeNode) other;
          return new EqualsBuilder()
                  .append(getName(), castOther.getName())
                  .isEquals();
      }
      

    toString

    1. Please ensure that toString will not throw NullPointerException.
    2. You may call for .appendSuper(super.toString()) in case your class is subclass

      @Override
      public String toString() {
          return new ToStringBuilder(this)
                  .append("Name", getName())
                  .toString();
      }
      

提交回复
热议问题