Ond*_*ala 3 validation spring integer notnull
我有实体:
public class User{
@NotNull
private Integer age;
}
Run Code Online (Sandbox Code Playgroud)
在休息控制器中:
@RestController
public UserController {
.....
}
Run Code Online (Sandbox Code Playgroud)
我有 BindingResult,但字段年龄 Spring 未验证。你能告诉我为什么吗?
感谢您的回答。
如果您发布了表示User类的JSON 数据之类的内容,您可以将注释@Valid与 @RequestBody 结合使用来触发对注释的验证,例如@NotNull您在您的age财产上拥有的注释。然后BindingResult您可以检查实体/数据是否有错误并进行相应处理。
@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
}
}
}
Run Code Online (Sandbox Code Playgroud)
我会确保你的User班级也有@Entity注释。
@Entity
public class User {
@NotNull
@Min(18)
private Integer age;
public Integer getAge() { return age; }
public setAge(Integer age) { this.age = age; }
}
Run Code Online (Sandbox Code Playgroud)
您可能希望设置输出/记录 SQL 的属性,以便您可以看到正确的限制正在添加到用户表中。
希望这有帮助!
| 归档时间: |
|
| 查看次数: |
27827 次 |
| 最近记录: |