仅在使用Spring Data查看特定项目时才公开某些字段? [英] Only expose certain fields when viewing specific item with Spring Data?

查看:68
本文介绍了仅在使用Spring Data查看特定项目时才公开某些字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm currently using Spring Boot to create a REST API with a mongodb backend. Is it possible to only expose certain fields when viewing a specific item, and not a list of items?

例如,在查看用户列表时,仅公开电子邮件,姓名和ID:

For example, when viewing a list of users, to only expose email, name, and 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"
    }
  ]
}

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

But expose extra fields, e.g. address and gender, when searching for a specific user:

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;

...
}

推荐答案

在使用Spring Data REST时,它为此专门设计了一些东西.有投影和摘录的概念投影和摘录可以指定要返回的内容和方式.

When using Spring Data REST it has something especially designed for this. There is the notion of Projections and Excerpts with it you can specify what and how you want to return it.

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

First you would create an interface which would contain only the fields you want.

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

然后在PersonRepository上将其添加为要使用的默认值(仅适用于返回集合的方法!).

Then on your PersonRepository add this as the default to use (will only apply to methods returning collections!).

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

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

Then when doing a query for a collection you will only get the fields as specified in the projection and when obtaining a single instance you will get the full object.

这篇关于仅在使用Spring Data查看特定项目时才公开某些字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆