@ -237,46 +237,12 @@ The following example shows a projecting DTO:
@@ -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.