Recommend Java records instead of Lombok for class-based projections.
Closes #2793 Original pull request: #2794
This commit is contained in:
committed by
Mark Paluch
parent
77de8aafff
commit
959bde4d37
@@ -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}[]
|
||||
|
||||
Reference in New Issue
Block a user