我正在尝试对名为 Institute
的实体类应用投影。
我定义了以下投影类。
@Projection(name = "instituteProjection", types = { Institute.class })
public interface InstituteProjection {
String getOrganizationName();
Contact getContact();
Address getRegisteredAddress();
Address getMailingAddress();
}
我遵循了 Oliver Gierke 的回答 link并且能够在调用 http://localhost:8080/institutes
时返回带有投影的集合资源。为此,我在服务层实现了以下方法,然后使用 REST Controller 调用它。
@Autowired
private ProjectionFactory projectionFactory;
@Autowired
InstituteTypeRepository instituteTypeRepo;
@Override
public PagedResources<Institute> getAllInstitutes(Pageable page) {
Page<?> instituteList = instituteRepo.findAll(page).
map(institute -> projectionFactory.createProjection(InstituteListProjection.class, institute));
PagedResources<Institute> instituteListPaged = pagedResourcesAssembler.toResource(instituteList);
return instituteListPaged;
}
现在如何在调用 http://localhost:8080/institutes/1
时将相同的投影应用于项目资源?
更新 1:
获取单个资源的 Controller 方法
@RequestMapping(value = "institutes/{instituteId}", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> getInstitute(@PathVariable Long instituteId) {
Institute institute = service.getInstitute(instituteId);
return new ResponseEntity<>(institute, HttpStatus.OK);
}
更新 2:
服务层方法从资源库获取单个资源
@Override
public Institute getInstitute(Long instituteId) {
Institute institute = instituteRepo.findOne(instituteId);
return institute;
}
最佳答案
你的问题有点不清楚。您可以自动将 Spring Data 存储库公开为 rest 资源,即您不需要定义自己的 Spring MVC Controller 。
http://docs.spring.io/spring-data/rest/docs/current/reference/html/#install-chapter
使用 SDR 存储库,定义为“摘录投影”的投影可以自动应用于集合资源:
http://docs.spring.io/spring-data/rest/docs/current/reference/html/#projections-excerpts.excerpts
但不是单一资源。对于单个资源,客户端必须通过请求参数指定所需的投影。
如果您想将投影自动应用于单个资源,那么这可能是实现您自己的 Controller 的原因(但是从您的问题中不清楚您是否正在这样做)。
对于将投影自动应用于单个资源的替代方法(即没有自定义 Controller ,请参见此处):
Spring Data REST: projection representation of single resource
如果您正在创建自定义 Controller 以自动应用投影,那么可以简单地编写一个返回投影而不是完整实体的自定义查询方法,并从您的 Controller /服务中调用它:
基本上,通过一些配置,您可以选择自动公开为 REST 资源的 Spring Data 存储库,而无需编写任何 Controller 代码。
关于java - Spring - 如何在单个资源上应用投影?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43555958/