ada*_*m p 4 java spring spring-data-rest spring-hateoas spring-boot
有没有办法使用@Projection接口作为SDR中资源的默认表示?通过SDR存储库还是通过自定义控制器?
过去可以通过注入ProjectionFactory和使用该createProjection方法在自定义控制器中执行此操作,但最近的Spring Data Rest更新已经破坏了这一点.
我想对一个实体强制执行一个特定的视图,SDR投影似乎是一个理想的方法,特别是在HAL API的上下文中,而不是为自定义控制器编写硬DTO类和它们之间的映射等.摘录预测不是我所追求的,因为这些只适用于查看相关资源.
ada*_*m p 13
要回答我自己的问题,现在有几种简单的方法可以做到这一点.
您可以默认使SDR存储库查找器返回投影:
public interface PersonRepository extends PagingAndSortingRepository<Person,Long> {
Set<PersonProjection> findByLastName(String lastName);
}
Run Code Online (Sandbox Code Playgroud)
您还可以通过使用@BasePathAwareController创建自定义Spring MVC控制器来有选择地覆盖SDR默认为您处理的响应.如果您计划提供分页响应,则需要注入ProjectionFactory和可能的PagedResourcesAssembler.
@BasePathAwareController
public class CustomPersonController {
@Autowired
private ProjectionFactory factory;
@Autowired
private PersonRepository personRepository;
@Autowired
private PagedResourcesAssembler<PersonProjection> assembler;
@RequestMapping(value="/persons", method = RequestMethod.GET, produces = "application/hal+json")
public ResponseEntity<?> getPeople(Pageable pageable) {
Page<Person> people = personRepository.findAll(pageable);
Page<PersonProjection> projected = people.map(l -> factory.createProjection(PersonProjection.class, l));
PagedResources<Resource<PersonProjection>> resources = assembler.toResource(projected);
return ResponseEntity.ok(resources);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7392 次 |
| 最近记录: |