Home United States USA — software Inheritance vs. Composition in JPA

Inheritance vs. Composition in JPA

60
0
SHARE

There are two approaches: Inheritance and Composition with their pros and cons. Let’s see what they are on the not quite “real-world” but representative example
Join the DZone community and get the full member experience. «Don’t repeat yourself» or «DRY». Developers try to adhere to this principle during software development. It helps to avoid redundant code writing and, as a result, simplifies its maintainability in the future. But how to achieve this principle in the JPA world? There are two approaches: Inheritance and Composition. Both have their pros and cons. Let’s figure out what they are on the not quite “real-world” but representative example. Our model has three entities: Article, Author, and Spectator. Each entity has fields for audit (createdDate, createdBy, modifiedDate, and modifedBy). Author and Spectator also have fields for address (country, city, street, building). To comply with the DRY principle, let’s take duplicate fields to the separate Mapped Superclasses. We will inherit our entities from them. Since all entities must have fields for auditing, let’s start with the BaseEntityAudit class. We will create a “BaseEntityAuditAddress” class for entities with address fields and inherit it from the BaseEntityAudit class.

Continue reading...