Skip to content

Recommend Java records instead of Lombok for class-based projections #2794

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 2 additions & 36 deletions src/main/asciidoc/repository-projections.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -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}[]
Expand Down