Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot, how to use @Valid with List<T>

I am trying to put validation to a Spring Boot project. So I put @NotNull annotation to Entity fields. In controller I check it like this:

@RequestMapping(value="", method = RequestMethod.POST)
public DataResponse add(@RequestBody @Valid Status status, BindingResult bindingResult) {
    if(bindingResult.hasErrors()) {
        return new DataResponse(false, bindingResult.toString());
    }

    statusService.add(status);

    return  new DataResponse(true, "");
}

This works. But when I make it with input List<Status> statuses, it doesn't work.

@RequestMapping(value="/bulk", method = RequestMethod.POST)
public List<DataResponse> bulkAdd(@RequestBody @Valid List<Status> statuses, BindingResult bindingResult) {
    // some code here
}

Basically, what I want is to apply validation check like in the add method to each Status object in the requestbody list. So, the sender will now which objects have fault and which has not.

How can I do this in a simple, fast way?

like image 368
kalahari Avatar asked Sep 06 '16 11:09

kalahari


1 Answers

My immediate suggestion is to wrap the List in another POJO bean. And use that as the request body parameter.

In your example.

@RequestMapping(value="/bulk", method = RequestMethod.POST)
public List<DataResponse> bulkAdd(@RequestBody @Valid StatusList statusList, BindingResult bindingResult) {
// some code here
}

and StatusList.java will be

@Valid
private List<Status> statuses;
//Getter //Setter //Constructors

I did not try it though.

Update: The accepted answer in this SO link gives a good explanation why bean validation are not supported on Lists.

like image 177
ameenhere Avatar answered Oct 23 '22 05:10

ameenhere