我正在尝试对名为的实体类应用投影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 控制器调用它来做到这一点。
@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:
获取单个资源的控制器方法
@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;
}