How to implement equals with hibernate without risking losing the symmetric property?

谁说我不能喝 提交于 2019-12-03 11:10:38

If you want to compare the classes of both objects in the equals method you can use Hibernate.getClass on both objects before comparing them. Then you don't run into trouble e.g. when comparing an object and a hibernate proxy for an object.

Beamie

After rading up some more i summarize this question with:

  • Use instanceof and you can never add significant members to subclasses.( There is no way to extend an instantiable class and add a value component while preserving the equals contract (Bloch)
  • Use getClass and you violate the Liskov substitution principle

Langers says http://www.angelikalanger.com/Articles/JavaSolutions/SecretsOfEquals/Equals.html

  • The instanceof test is correct only for final classes or if at least method equals() is final in a superclass. The latter essentially implies that no subclass must extend the superclass's state, but can only add functionality or fields that are irrelevant for the object's state and behavior, such as transient or static fields.

Implementations using the getClass() test on the other hand always comply to the equals() contract; they are correct and robust. They are, however, semantically very different from implementations that use the instanceof test. Implementations using getClass() do not allow comparison of sub- with superclass objects, not even when the subclass does not add any fields and would not even want to override equals() . Such a "trivial" class extension would for instance be the addition of a debug-print method in a subclass defined for exactly this "trivial" purpose. If the superclass prohibits mixed-type comparison via the getClass() check, then the trivial extension would not be comparable to its superclass. Whether or not this is a problem fully depends on the semantics of the class and the purpose of the extension.

Summary - use instanceof with final for equals avoids breaking symmetry, and avoids the hibernate "proxy" problem.

Links

This is an interesting question - implementing equals as an equivalence relation is not trivial when inheritance is involved. See this in-depth post by Martin Odersky et al. about implementing object equality.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!