Like all object-oriented programing languages, Java supports the fundamental concepts of inheritance and composition. There is an important difference between both concepts. Inheritance enables you to model an is-a association between two classes by extending a superclass. Composition models a has-a association by referencing another class in an instance variable.
You can use both concepts with JPA and Hibernate. But when should you use which one and what is the best way to do that?
For plain Java classes, there have been hundreds of discussions about this question. And there is a clear winner.
Inheritance vs. Composition for Plain Java Classes
In most cases, you should prefer composition when you design plain Java classes. In his book Effective Java 3rd Edition Joshua Bloch describes 2 circumstances in which it’s OK to use inheritance:
“It is safe to use inheritance within a package, where the subclass and the superclass implementations are under the control of the same programmers. It is also safe to use inheritance when extending classes specifically designed and documented for extension.”
Joshua Bloch – Effective Java 3rd Edition (Book Review)
In my experience, most classes in most projects were created to solve a specific task but nobody thought about extending them in the future. So, they are not designed for it and you shouldn’t extend them. If you do it anyways, you will most likely experience unexpected side-effects and implementation lock-ins in future releases.
But all these discussions and recommendations are for plain Java classes. Is this also valid for entity classes annotated with JPA annotations and mapped to tables in a relational database? And how should you implement the mapping?