Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - validation of Integer attribute

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.

like image 905
Ondra Pala Avatar asked Oct 29 '25 05:10

Ondra Pala


2 Answers

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!

like image 127
Alexander Staroselsky Avatar answered Oct 31 '25 19:10

Alexander Staroselsky


If needed you can specifiy default messages

@NotNull("message": "age: positive number value is required")

@Min(value=18, message="age: positive number, min 18 is required")

and please use dto's

like image 25
Suvarna Avatar answered Oct 31 '25 20:10

Suvarna



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!