【问题标题】:Only expose certain fields when viewing specific item with Spring Data?仅在使用 Spring Data 查看特定项目时公开某些字段?
【发布时间】:2016-09-23 18:15:12
【问题描述】:

我目前正在使用 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"
    }
  ]
}

但要公开额外的字段,例如搜索特定用户时的地址和性别:

GET /{endpoint}/users/57420f340d31cd8a1f74a84e

{
  "email": "some_other_email@gmail.com",
  "name": "some other name",
  "address": "1234 foo street"
  "gender": "female"
  "id": "57420f340d31cd8a1f74a84e"
}

给定一个用户类:

public class User {

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

...
}

【问题讨论】:

  • 这就是Projections and Excerpts 的用途。您可以指定您想要的内容以及如何显示。假设您使用的是 Spring Data REST,那就是。如果您有自己的自定义控制器,只需根据需要创建一个 DTO。
  • 快速查看文档,看来这正是我想要的。谢谢!
  • @M.Deinum — 这应该是一个答案! :)

标签: spring mongodb spring-boot spring-data


【解决方案1】:

当使用 Spring Data REST 时,它有专门为此设计的东西。有Projections and Excerpts 的概念,您可以指定要返回的内容和方式。

首先,您将创建一个只包含您想要的字段的界面。

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

然后在您的PersonRepository 上添加它作为默认使用(仅适用于返回集合的方法!)。

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

然后,在查询集合时,您将只获得投影中指定的字段,而在获得单个实例时,您将获得完整的对象。

【讨论】:

  • 正是我要找的,也谢谢你的例子!
【解决方案2】:

你必须在仓库的find方法上添加@Query注解并指定fields参数:

public interface PersonRepository extends MongoRepository<Person, String>

  @Query(value="{ 'firstname' : ?0 }", fields="{ 'firstname' : 1, 'lastname' : 1}")
  List<Person> findByThePersonsFirstname(String firstname);

}

见:http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongodb.repositories.queries.json-based

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    相关资源
    最近更新 更多