It can be easily done in the lates Spring Data Rest releases!
All you need to do is to:
pass projection name as request param
`/api/users/search/findEmployeeUsers?projection=userView`
return PagedModel<PersistentEntityResource>
instead of Page<User>
from your service method;
Done!
and I assume you want to call this service method from your custom controller, in this case you need to return ResponseEntity<PagedModel<PersistentEntityResource>>
from your controller method.
Don't want it pageable? Simply return ResponseEntity<CollectionModel<PersistentEntityResource>>
instead.
Also check out example for single resoure projection.
Spring Data Rest takes care of applying @Projection
s to PersistentEntityResource
s on api requests, it's just like you keep exposing your @RestResource
from @RepositoryRestResource
; same behaviour for projections, keeping same naming convention, basically same URI (for current example).
Your service method with a bit of bussiness logic might look like:
@Override
@Transactional(readOnly = true)
public PagedModel<PersistentEntityResource> listEmployees(Pageable pageable, PersistentEntityResourceAssembler resourceAssembler) {
Page<User> users = userRepository.findEmployeeUsers(pageable);
List<User> entities = users.getContent();
entities.forEach(user -> user.setOnVacation(isUserOnVacationNow(user)));
CollectionModel<PersistentEntityResource> collectionModel = resourceAssembler.toCollectionModel(entities);
return PagedModel.of(collectionModel.getContent(), new PagedModel.PageMetadata(
users.getSize(),
users.getNumber(),
users.getTotalElements(),
users.getTotalPages()));
}
and your controller method might look like this:
@BasePathAwareController
public class UsersController {
@GetMapping(value = "/users/search/findEmployeeUsers")
ResponseEntity<PagedModel<PersistentEntityResource>> findEmployeeUsers(Pageable pageable,
PersistentEntityResourceAssembler resourceAssembler) {
return ResponseEntity.status(HttpStatus.OK)
.body(userService.listEmployees(pageable, resourceAssembler));
}
}
I'm using spring-boot-starter-data-rest:2.3.4.RELEASE with spring-data-rest-webmvc:3.3.4.RELEASE and spring-data-rest-webmvc:3.3.4.RELEASE as dependencies, configuring it as parent of my pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>