I am stuck in an obviously simple problem: I want to do some random check based on the identifier of an object in a PUT request.
@RequestMapping(value="/{id}", method=RequestMethod.PUT) public ResponseEntity<Void> update(@Valid @RequestBody ClientDTO objDto, @PathVariable Integer id) { Client obj = service.fromDTO(objDto); service.update(obj); return ResponseEntity.noContent().build(); }
I would like to create a special validator to display a special message in case I update some field that cannot be the same other object in my database. Something like that:
public class ClientUpdateValidator implements ConstraintValidator<ClientUpdate, ClientDTO> { @Autowired private ClientRepository repo; @Override public void initialize(ClientInsert ann) { } @Override public boolean isValid(ClientDTO objDto, ConstraintValidatorContext context) { Client aux = repo.findByName(objDto.getName()); if (aux != null && !aux.getId().equals(objDto.getId())) { context.disableDefaultConstraintViolation(); context.buildConstraintViolationWithTemplate("Already exists") .addPropertyNode("name").addConstraintViolation(); return false; } return true; } }
However, the object identifier comes from @PathVariable, not from @RequestBody. I can not name "objDto.getId ()", as I said above.
On the other hand, it makes no sense to oblige to fill out the identifier of the object in the request body, because in this way the path variable will become hopeless.
How can I solve this problem? Is there a way to insert an identifier from a PathVariable into a RequestBody object prior to bean authentication? If not, what would be a viable solution? Thanks.
source share