From 539106302642fc3482919f2c9083368e3d05552a Mon Sep 17 00:00:00 2001 From: Tim Feuerbach Date: Sun, 19 Mar 2023 13:44:44 +0100 Subject: [PATCH] Recommend records instead of Lombok for class based projections. Closes #2793 --- src/main/asciidoc/repository-projections.adoc | 38 +------------------ 1 file changed, 2 insertions(+), 36 deletions(-) diff --git a/src/main/asciidoc/repository-projections.adoc b/src/main/asciidoc/repository-projections.adoc index 3a1c2ad2b9..d2340916d5 100644 --- a/src/main/asciidoc/repository-projections.adoc +++ b/src/main/asciidoc/repository-projections.adoc @@ -237,46 +237,12 @@ The following example shows a projecting DTO: ==== [source, java] ---- -class NamesOnly { - - private final String firstname, lastname; - - NamesOnly(String firstname, String lastname) { - - this.firstname = firstname; - this.lastname = lastname; - } - - String getFirstname() { - return this.firstname; - } - - String getLastname() { - return this.lastname; - } - - // equals(…) and hashCode() implementations +record NamesOnly(String firstname, String lastname) { } ---- ==== -[TIP] -.Avoid boilerplate code for projection DTOs -==== -You can dramatically simplify the code for a DTO by using https://projectlombok.org[Project Lombok], which provides an `@Value` annotation (not to be confused with Spring's `@Value` annotation shown in the earlier interface examples). -If you use Project Lombok's `@Value` annotation, the sample DTO shown earlier would become the following: - -[source,java] ----- -@Value -class NamesOnly { - String firstname, lastname; -} ----- - -Fields are `private final` by default, and the class exposes a constructor that takes all fields and automatically gets `equals(…)` and `hashCode()` methods implemented. - -==== +Records are ideal DTOs since they adhere to value semantics (all fields are private final, `equals(…)` and `hashCode()` are provided by default), but you are free to use any class with a constructor listing the fields to be retrieved. ifdef::repository-projections-trailing-dto-fragment[] include::{repository-projections-trailing-dto-fragment}[]