Spring - validation of Integer attribute

Ondra Pala picture Ondra Pala · Jan 19, 2017 · Viewed 26k times · Source

I have entity:

public class User{
   @NotNull
   private Integer age;
} 

In Restcontroller:

@RestController
public UserController {
 ..... 
} 

I have BindingResult, but field age Spring doesn't validate. Can you tell me why?

Thanks for your answers.

Answer

Alexander Staroselsky picture Alexander Staroselsky · Jan 19, 2017

If your posting something like JSON data representing the User class you can use the annotation @Valid in conjunction with @RequestBody to trigger validation of annotations such as the @NotNull you have on your age property. Then with BindingResult you can check if the entity/data has errors and handle accordingly.

@RestController
public UserController {

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<?> create(@Valid @RequestBody User user, BindingResult bindingResult) {
        if(bindingResult.hasErrors()) {
            // handle errors
        }
        else {
            // entity/date is valid
        }
    }
}

I'd make sure your User class also has the @Entity annotation as well.

@Entity
public class User {
    @NotNull
    @Min(18)
    private Integer age;

    public Integer getAge() { return age; }

    public setAge(Integer age) { this.age = age; }
}

You may want to set properties to output/log SQL so that you can see that the proper restraints are being added to the User table.

Hopefully that helps!