Only expose certain fields when viewing specific item with Spring Data?

后端 未结 2 1931
[愿得一人]
[愿得一人] 2021-01-16 21:21

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 it

相关标签:
2条回答
  • 2021-01-16 22:05

    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();
    }
    

    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.

    0 讨论(0)
  • 2021-01-16 22:12

    You have to add @Query annotation on the find method in the repository and specify the fields parameter:

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

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

    0 讨论(0)
提交回复
热议问题