简体   繁体   中英

Question regarding Hashcode and Equals and toString method in Entities

I want to know the rules what instance variables should be included when overriding hashcode and equals method when we are working with entities which has one to many relations.

Have this entity where User has many Contacts, so contact class has obviosly an instance variable User user. so when i select all the fields when overriding hashcode and equals method, it says stackoverflowError in toString method.

Your error is logic as I guess you have a bidirectional relation and you references entity.equals/hashcode on both side.. so an infinite cycle is made.

Remove the call to equals/hashcode contract on the entity directly either on User.contact or on Contact.user equals/hash implementation.

This will solve your problem.

You are getting the error because of the bidirectional association. But more importantly, the identity of an entity should not depend on the associated entities. Hash code and equality should only depend on the attribute of your User entity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM