Inheriting Properties for Lombok @Builders and JPA Entities

Home » Blog » Software » Enterprise Software » Inheriting Properties for Lombok @Builders and JPA Entities

Leider ist der Eintrag nur auf Britisches Englisch verfügbar.

Lombok is one of those helpful developer tools for the Java language ecosystem that streamline (or even do away with entirely) the more tedious and mundane tasks in software development. Lombok in particular vastly reduces the boilerplate code Java developers have to write by providing annotations that have code for common structures and patterns such as constructors, getters and setters, and builders automatically generated.

While tremendously helpful, sometimes edge cases can occur when working with theses kinds of abstractions and as a result those abstractions can become leaky and either reveal the implementation or require code duplication to achieve the desired result. One such edge case is using the @Builder annotation linked to above for classes extending another class, since a @Builder on a child class doesn’t have access to properties from its parent class:

To alleviate this problem we can use @SuperBuilder, which gives us access to properties from the parent class, too, when using the builder pattern through Lombok:

Similarly, when working with JPA and abstract class inheritance, we can avoid code duplication in child classes by using the @MappedSuperclass annotation (from the Jakarta Persistence API), which will inherit JPA properties like @Id or @GeneratedValue from a parent class. Java persistence expert Vlad Mihalcea has an excellent article on the matter:

How to inherit properties from a base class entity using @MappedSuperclass with JPA and Hibernate

About the author: Bjoern
Independent IT consultant, entrepreneur

Leave a Comment