0Pricing
Spring Boot 4 Microservices & REST APIs · Lekcja

Projekcje i DTO

Wybieraj tylko potrzebne dane

Projekcje i DTO to bezpłatna lekcja Spring Boot 4 Microservices & REST APIs na CoddyKit. To lekcja 2 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Spring Boot 4 Microservices & REST APIs, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Spring Boot 4 Microservices & REST APIs zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

Why Projections

Fetching whole entities when you need only a few columns wastes memory and bandwidth.

Projections let you select a subset of fields, returning lightweight objects instead of full entities.

Interface Projections

Declare an interface with getters for the fields you want. Spring Data implements it as a proxy.

public interface UserSummary {
    String getName();
    String getEmail();
}

Returning a Projection

Use the interface as the query method return type.

public interface UserRepository
    extends JpaRepository<User, Long> {
    List<UserSummary> findByActiveTrue();
}

Closed vs Open Projections

A closed projection only exposes existing properties (efficient — selects only those columns). An open projection computes values with @Value and SpEL (loads the whole entity).

Open Projection Example

Combine fields with a SpEL expression.

public interface UserView {
    @Value("#{target.firstName + ' ' + target.lastName}")
    String getFullName();
}

Class-Based Projections (DTOs)

A DTO class with a matching constructor is another projection style. Spring Data maps query columns to constructor parameters by name.

public class UserDto {
    private final String name;
    private final String email;

    public UserDto(String name, String email) {
        this.name = name;
        this.email = email;
    }
    // getters
}

Returning a DTO

Use the DTO class as the return type, just like interface projections.

public interface UserRepository
    extends JpaRepository<User, Long> {
    List<UserDto> findByActiveTrue();
}

DTOs in JPQL Constructor Expressions

With custom JPQL, use a constructor expression to build DTOs directly.

@Query("SELECT new com.app.UserDto(u.name, u.email) "
     + "FROM User u WHERE u.active = true")
List<UserDto> findActiveSummaries();

Dynamic Projections

Make the return type generic so one method serves multiple projections.

<T> List<T> findByActiveTrue(Class<T> type);

// usage
repo.findByActiveTrue(UserSummary.class);
repo.findByActiveTrue(UserDto.class);

Projections with Native Queries

Interface projections also work with native SQL queries when column names match the getters.

@Query(value = "SELECT name, email FROM users",
       nativeQuery = true)
List<UserSummary> findAllSummaries();

Choosing an Approach

Prefer closed interface projections for read-only lists (most efficient). Use DTO classes when you need behavior or want them outside the persistence layer.

Quick Check

Test your understanding of projections.

Recap

You learned to return lightweight results:

  • Interface projections — closed (efficient) or open (SpEL)
  • Class-based DTO projections via constructor mapping
  • JPQL constructor expressions for custom queries
  • Dynamic projections with a generic type parameter

Często zadawane pytania

Czy lekcja „Projekcje i DTO” jest bezpłatna?

Tak — pełny tekst „Projekcje i DTO” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Spring Boot 4 Microservices & REST APIs, przejdź na CoddyKit PRO. Kurs Spring Boot 4 Microservices & REST APIs zawiera 4 lekcji w sumie.

Co nauczysz się w „Projekcje i DTO”?

Wybieraj tylko potrzebne dane Ćwiczysz Spring Boot 4 Microservices & REST APIs z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Spring Boot 4 Microservices & REST APIs?

Nie wymagamy żadnego doświadczenia. Spring Boot 4 Microservices & REST APIs w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 2 z 4.

Ile czasu zajmuje lekcja „Projekcje i DTO”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Spring Boot 4 Microservices & REST APIs?

Tak. Każda lekcja Spring Boot 4 Microservices & REST APIs zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Dynamiczne zapytania ze Specifications
  2. Projekcje i DTO
  3. Audytowanie za pomocą @CreatedDate
  4. Stronicowanie i sortowanie
← Powrót do Spring Boot 4 Microservices & REST APIs