To equals and hashcode or not on entity classes, that is the question

后端 未结 2 676
灰色年华
灰色年华 2021-01-18 09:48

I have been trying to reason about the best way to handle whether it is generally good practice to implement hashcode and equals on entities (I mean entity in the general se

相关标签:
2条回答
  • 2021-01-18 10:02

    I've tried this before on a large scale (or at least in an application that heavily uses hibernate). It's a good idea.

    It makes sense to have .equals and .hashcode include only these natural keys but what if you have more than one instance of the same entity (same natural id thus same hashcode)? It seems like this practice could have subtle implications elsewhere in your application.

    This is what it's meant for. You typically want multiple instances of the same entity to succeed when comparing .equals, and yes, it has implications elsewhere. IMO those implications are that things would work as expected.

    0 讨论(0)
  • 2021-01-18 10:05

    There are times when you want Equals to compare all properties and times when you want Equals to be just the key. We've had a lot more success using helper classes that are explicit so there isn't ambiguity as to what's being compared.

    ByKeyComparer.Equals...
    ByPropertiesComparer.Equals...
    

    or

    Entity1.EqualsByKey...
    Entity1.EqualsByProperties...
    
    0 讨论(0)
提交回复
热议问题