使用Spring Data查看特定项目时只显示某些字段?

Kev*_*ant 0 spring mongodb spring-data spring-boot

我目前正在使用Spring Boot创建一个带有mongodb后端的REST API.是否可以在查看特定项目时仅显示某些字段,而不是项目列表?

例如,在查看用户列表时,仅显示电子邮件,名称和ID:

GET /{endpoint}/users

{
  "_embedded": {
  "users": [
    {
      "email": "some_email@gmail.com",
      "name": "some name",
      "id": "57420b2a0d31bb6cef4ee8e9"
    }, 
    {
      "email": "some_other_email@gmail.com",
      "name": "some other name",
      "id": "57420f340d31cd8a1f74a84e"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

但是在搜索特定用户时会暴露额外的字段,例如地址和性别:

GET /{endpoint}/users/57420f340d31cd8a1f74a84e

{
  "email": "some_other_email@gmail.com",
  "name": "some other name",
  "address": "1234 foo street"
  "gender": "female"
  "id": "57420f340d31cd8a1f74a84e"
}
Run Code Online (Sandbox Code Playgroud)

给定一个用户类:

public class User {

    private String id;
    private String email;
    private String address;
    private String name;
    private String gender;

...
}
Run Code Online (Sandbox Code Playgroud)

M. *_*num 6

使用Spring Data REST时,它有一些特别为此设计的东西.有预测和摘录的概念,您可以指定您想要返回的内容和方式.

首先,您将创建一个仅包含所需字段的界面.

@Projection(name="personSummary", types={Person.class})
public interface PersonSummary {
    String getEmail();
    String getId();
    String getName();
}
Run Code Online (Sandbox Code Playgroud)

然后在你PersonRepository添加它作为默认使用(将只适用于返回集合的方法!).

@RepositoryRestResource(excerptProjection = PersonSummary.class)
public interface PersonRepository extends CrudRepository<Person, String> {}
Run Code Online (Sandbox Code Playgroud)

然后,当对集合进行查询时,您将只获得投影中指定的字段,并且在获取单个实例时,您将获得完整对象.