0Pricing
Spring Boot 4 Microservices & REST APIs · 课时

投影和 DTO

仅选择所需的数据

投影和 DTO 是 CoddyKit 上的免费 Spring Boot 4 Microservices & REST APIs 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Spring Boot 4 Microservices & REST APIs 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Spring Boot 4 Microservices & REST APIs 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

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

常见问题解答

「投影和 DTO」课时是免费的吗?

是的 — 「投影和 DTO」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Spring Boot 4 Microservices & REST APIs 课程的其余内容,请升级到 CoddyKit PRO。 Spring Boot 4 Microservices & REST APIs 课程共包含 4 节课。

「投影和 DTO」这节课中我会学到什么?

仅选择所需的数据 你通过在浏览器中直接运行的动手代码来练习 Spring Boot 4 Microservices & REST APIs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Spring Boot 4 Microservices & REST APIs 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Spring Boot 4 Microservices & REST APIs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「投影和 DTO」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Spring Boot 4 Microservices & REST APIs 课中编写并运行代码吗?

能。每节 Spring Boot 4 Microservices & REST APIs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用规范构建动态查询
  2. 投影和 DTO
  3. 使用 @CreatedDate 进行审计
  4. 分页和排序
← 返回 Spring Boot 4 Microservices & REST APIs