简体   繁体   English

关于实体中 Hashcode 和 Equals 和 toString 方法的问题

[英]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.当我们使用具有一对多关系的实体时,我想知道在覆盖哈希码和 equals 方法时应该包含哪些实例变量的规则。

Have this entity where User has many Contacts, so contact class has obviosly an instance variable User user.有这个实体,用户有很多联系人,所以联系人 class 显然有一个实例变量用户用户。 so when i select all the fields when overriding hashcode and equals method, it says stackoverflowError in toString method.所以当我 select 覆盖哈希码和等于方法时的所有字段时,它会在 toString 方法中显示 stackoverflowError 。

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.你的错误是逻辑,因为我猜你有一个双向关系并且你在两边都引用entity.equals/hashcode ..所以一个无限循环。

Remove the call to equals/hashcode contract on the entity directly either on User.contact or on Contact.user equals/hash implementation.直接在User.contactContact.user equals/hash 实现上删除实体上对 equals/hashcode 合约的调用。

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. Hash 代码和相等性应仅取决于您的用户实体的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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