我正在使用Spring Boot创建一个Rest API,并且正在使用Hibernate Validation来验证请求输入。
但是我还需要其他类型的验证,例如,当需要检查更新数据时,如果公司ID不存在,我想抛出一个自定义异常。
该验证应该位于服务层还是控制器层?
服务层:
public Company update(Company entity) {
if (entity.getId() == null || repository.findOne(entity.getId()) == null) {
throw new ResourceNotFoundException("can not update un existence data with id : "
+ entity.getId());
}
return repository.saveAndFlush(entity);
}
控制器层:
public HttpEntity<CompanyResource> update(@Valid @RequestBody Company companyRequest) {
Company company = companyService.getById(companyRequest.getId());
Precondition.checkDataFound(company,
"Can't not find data with id : " + companyRequest.getId());
// TODO : extract ignore properties to constant
BeanUtils.copyProperties(companyRequest, company, "createdBy", "createdDate",
"updatedBy", "updatedDate", "version", "markForDelete");
Company updatedCompany = companyService.update(company);
CompanyResource companyResource = companyAssembler.toResource(updatedCompany);
return new ResponseEntity<CompanyResource>(companyResource, HttpStatus.OK);
}