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

后端 未结 7 2079
青春惊慌失措
青春惊慌失措 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

    As already mentioned you have to use a business key to implement equal and hashCode. Additionally you have to make your equals and hashCode implementation null-safe or add not null contraints (and invariant checks into your code) to ensure that the business key is never null.

    I suppose adding constraints is the right approach for your problem. Otherwise Role instances without names would be allowed and all these physical instances would be considered equal.

提交回复
热议问题