I'm creating a Rest API using Spring Boot and I am using Hibernate Validation to validate request inputs.
But I also need other kinds of validation, for example when update data needs to checked, if the company id doesn't exist I want to throw a custom exception.
Should this validation be located at the service layer or the controller layer?
Service Layer :
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);
}
Controller Layer :
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);
}