本文介绍了使用Spring Data Rest @Projection作为自定义控制器中资源的表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用@Projection接口作为SDR中资源的默认表示?通过SDR存储库还是通过自定义控制器?

Is there any way to use a @Projection interface as the default representation for a resource in SDR? Either through the SDR repositories or through a custom controller?

过去可以在自定义控制器中通过注入 ProjectionFactory 并使用<$ c来实现$ c> createProjection 方法,但最近的Spring Data Rest更新已经打破了这个问题。

It used to be possible in a custom controller to do this by injecting a ProjectionFactory and using the createProjection method, but this has been broken by a recent Spring Data Rest update.

我想在实体上强制执行特定视图,SDR投影看起来像是一种理想的方法,特别是在HAL API的上下文中,反对为自定义控制器编写硬DTO类并在它们之间进行映射等。摘录投影不是我所追求的,因为这些仅适用于查看关联资源时。

I would like to enforce a particular view on an entity, and the SDR projections seem like an ideal method for doing this, especially in the context of a HAL API, as opposed to writing hard DTO classes for a custom controller and mapping between them etc. Excerpt projections are not what I am after, as these only apply when looking at an associated resource.

推荐答案

要回答我自己的问题,现在有几种简单的方法可以做到这一点。

To answer my own question, there's now a couple of easyish ways to do this.

默认情况下,您可以让SDR存储库查找器返回投影:

You can make SDR repository finders return projections by default:

public interface PersonRepository extends PagingAndSortingRepository<Person,Long> {

    Set<PersonProjection> findByLastName(String lastName);

}

您还可以有选择地覆盖SDR为其处理的响应默认情况下,您可以使用@BasePathAwareController创建自定义Spring MVC控制器。如果您计划提供分页响应,则需要注入ProjectionFactory和可能的PagedResourcesAssembler。

You can also selectively override responses that SDR would have handled for you by default by creating a custom Spring MVC controller with the @BasePathAwareController. You will need to inject the ProjectionFactory and possibly the PagedResourcesAssembler if you're planning on providing a paged response.

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

这篇关于使用Spring Data Rest @Projection作为自定义控制器中资源的表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-28 11:01