Smajl
Smajl

Reputation: 7995

Spring projections without Spring Data REST

spring-data-rest provides a fantastic way how to specify the view of an entity - Spring projections. I am curious if there is a way for achieving similar functionality without using spring-data-rest - just repositories and simple rest controllers.

Let's say I have an entity:

@Entity
public class Customer {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  private String firstname;
  private String lastname;

  // … 
}

and two controller endpoints. One should return the full entity and the second only subset of the entity (eq. just firstname, although the real example is a bit more complex). Basically, I would like to avoid returning nested collections from some endpoints.

I know that I can achieve this by creating a second entity pointing to the same table that contains only the values needed but the problem is that I would have to create a separate repository for it as well and it creates a lot of unnecessary boilerplate.

So my question is, do I need to have two entities with two separate repositories or is there some more elegant way how to do this in Spring?

Upvotes: 1

Views: 858

Answers (2)

mtshaikh
mtshaikh

Reputation: 678

You could use JSON Views to filter out the fields you need. Here are some examples.

Alternatively you could create a DTO instead of a full entity but that is, IMHO an elegant approach.

Upvotes: 1

S.K.
S.K.

Reputation: 3677

You can use Spring's property filters to filter out few fields from response to an API:

@RequestMapping(...)
public MappingJacksonValue getUserEntities(...) 
    Page<UserEntity> entities = service.findAll();
    MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(entities);
    FilterProvider filters = new SimpleFilterProvider()
                .addFilter("UserEntity", SimpleBeanPropertyFilter
                        .filterOutAllExcept("fieldName"));
    mappingJacksonValue.setFilters(filters);
    return mappingJacksonValue;
}

Upvotes: 3

Related Questions