You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过REST API Projection返回集合大小?附示例代码

Absolutely! You can totally return the size of a collection using REST API Projections in Spring Data REST. Let me walk you through a couple of straightforward approaches tailored to your existing code setup:

This is the most common and lightweight way to create a projection. We'll define an interface that specifies exactly what data we want to expose, including the size of the users collection.

import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.rest.core.config.Projection;

@Projection(name = "userCountProjection", types = MyData.class)
public interface MyDataUserCountProjection {
    // Include any other fields you want to expose (e.g., the entity ID)
    Long getId();

    // Use SpEL to calculate the collection size directly from the entity
    @Value("#{target.users.size()}")
    Integer getUserCount();
}

How to use it:

Since your MyDataRepository already extends PagingAndSortingRepository, you just need to add the projection parameter to your API request. For example:
GET /myDatas/1?projection=userCountProjection

The response will look something like this (JSON):

{
  "id": 1,
  "userCount": 5,
  "_links": { ... }
}
2. Class-based Projection (For More Complex Logic)

If you need to add custom processing logic beyond simple field access, a class-based projection works well. We'll create a DTO that maps from your MyData entity and calculates the collection size in its constructor.

import org.springframework.data.rest.core.config.Projection;

@Projection(name = "userCountDtoProjection", types = MyData.class)
public class MyDataUserCountDto {
    private final Long id;
    private final Integer userCount;

    // Spring will automatically inject the MyData instance here
    public MyDataUserCountDto(MyData myData) {
        this.id = myData.getId();
        // Calculate the size of the users collection
        this.userCount = myData.getUsers().size();
    }

    // Getters are required for Spring to serialize the fields
    public Long getId() {
        return id;
    }

    public Integer getUserCount() {
        return userCount;
    }
}

How to use it:

Same as the interface approach—just specify the projection name in your request:
GET /myDatas/1?projection=userCountDtoProjection

Key Notes
  • Lazy Loading Consideration: Your users collection uses FetchType.LAZY, which means accessing size() will trigger a lazy load to fetch the collection data. If performance is a concern, you can either:
    • Switch to FetchType.EAGER (not always ideal for large collections)
    • Use @EntityGraph on your repository methods to preload the users collection
  • Default Projection: If you want this projection to be the default response for all MyData requests, add defaultProjection = true to the @Projection annotation:
    @Projection(name = "userCountProjection", types = MyData.class, defaultProjection = true)
    

内容的提问来源于stack exchange,提问作者sotix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:26:52