To reduce boilerplate code in the entities layer (and other Java classes, such as POJOs or DTOs), you can add Lombok annotations. These annotations generate repetitive code (e.g., getters, setters, constructors) at compile time, making the code cleaner and more maintainable.
Good Reference: https://www.baeldung.com/intro-to-project-lombok
Lombok is a helper third-party library designed to reduce boilerplate code in Java classes, particularly in the POJO layer (e.g., entities, DTOs), by using annotations. It generates code for common tasks (e.g., constructors, getters/setters, toString, equals, hashCode) during compilation, improving developer productivity and code readability.
Add Lombok Dependency in pom.xml
:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.34</version> <!-- Use the latest version, e.g., 1.18.34 -->
<scope>provided</scope>
</dependency>
Install Lombok Library to IDE:
Locate the Lombok JAR in your Maven repository:
<home dir>\\\\.m2\\\\repository\\\\org\\\\projectlombok\\\\lombok\\\\1.18.34\\\\lombok-1.18.34.jar
Run the Lombok installer:
Open a terminal or command prompt (run as administrator).
Execute:
java -jar lombok-1.18.34.jar
Specify the IDE location (e.g., Spring Tool Suite - STS):
C:\\\\sts-bundle\\\\sts-4.x.RELEASE\\\\STS.exe
Follow the installer prompts to integrate Lombok with the IDE.
Maven Force Update and Cleaning:
mvn clean install
to ensure dependencies are resolved.Use Lombok Annotations:
public Restaurant() {}
.public Restaurant(String name, String address, String city, String description, List<FoodItem> foodItems)
.final
or @NonNull
fields.public String getName() { return name; }
.public void setName(String name) { this.name = name; }
.toString()
method.exclude
: Excludes specified fields (e.g., exclude = {"foodItems"}
to avoid printing collections).callSuper = true
: Includes the superclass’s toString()
output (e.g., fields from BaseEntity
).@Getter
, @Setter
, @ToString
, @EqualsAndHashCode
, and @RequiredArgsConstructor
.Restaurant
, FoodItem
) due to potential issues with Hibernate (e.g., unintended equals
/hashCode
behavior affecting entity identity). Suitable for DTOs.equals()
and hashCode()
methods.log
field for logging (e.g., log.info("Message");
).