Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation in @RepositoryRestController

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;
}
like image 233
Jan Meier Avatar asked Feb 01 '26 23:02

Jan Meier


1 Answers

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);
}
like image 97
marknote Avatar answered Feb 04 '26 16:02

marknote



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!