July 17, 2012
“..but equals should usually compare state, not identity. This is particularly true for “data-centric” classes which map to database records. […] If you extend a concrete class, and add a new field which contributes to equals, then it is not possible to write a perfectly correct equals method for the new class. Instead, you should use composition instead of inheritance. (See Effective Java by Joshua Bloch for more information.) ”
This can be interpreted as “It’s not a good idea to use inheritance in, for example, JPA Entities. It’s better to use composition”. I tend to agree. Deep hierarchies of JPA entities, can be a daunting task to understand, maintain and extends. Having small hierarchies, I think it’s ok. If a JPA model, most of the time models real world concepts, and if real world concepts are better described in terms of composition, instead of inheritance, why complicate things? Take the typical Car exercise, would you model most of your car using inheritance or composition?
But if you’re modelling your JPA entities with object oriented principles , not caring about the mapping stuff, for now, everything that you will need to store in a DB are value types, like Integer, Long, String, byte, or some composition of these and other value types, so there’s no point to inherit just to add values to an object, it’s better to create a new value type that represents the concept.