I'd like to validate my DTO in my @RepositoryRestController with the javax annotation @Valid.
However @RepositoryRestController doesn't currently support @Valid as you can see in this ticket: https://jira.spring.io/browse/DATAREST-593
If I use a @RestController my @Valid would work fine, however then my @RepositoryRestResource wouldn't work anymore. I would need to manually write a method in my @RestController for each functionality (findOne(), findAll() etc.). Currently I can just use the @RepositoryRestResource with a Projection for the methods findAll() etc.
How do I validate the DTOs in a @RepositoryRestController?
Repository:
@RepositoryRestResource(excerptProjection = ChipProjection.class)
public interface ChipRepository extends JpaRepository<Chip, Long> {
}
Projection:
@Projection(name = "summary", types = Chip.class)
public interface ChipProjection {
Long getId();
ChipIdentifier getChipIdentifier();
}
Controller:
@RepositoryRestController
public class ChipRestController {
@Autowired
ChipService chipService;
@RequestMapping(value = "/chips", method = RequestMethod.POST)
public @ResponseBody ChipHelper saveChip(@Valid @RequestBody ChipHelper chip, BindingResult result){
List<FieldError> errors = result.getFieldErrors();
//errors is always empty, @Valid not working
chipService.save(chip);
return chip;
}
}
ChipHelper:
@Data
public class ChipHelper {
@NotNull
private Long id;
@NotNull
@Size(min = 10)
private String identifier;
}
This answer: https://stackoverflow.com/a/44304198/5435182 works for me:
Just add this to your @RepositoryRestController :
@Inject
private LocalValidatorFactoryBean validator;
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.addValidators(validator);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With