我有实体:
public class User{
@NotNull
private Integer age;
}
在休息 Controller 中:
@RestController
public UserController {
.....
}
我有 BindingResult,但字段 Age 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
}
}
}
我会确保您的 User
类也具有 @Entity
注释。
@Entity
public class User {
@NotNull
@Min(18)
private Integer age;
public Integer getAge() { return age; }
public setAge(Integer age) { this.age = age; }
}
您可能需要设置属性来输出/记录 SQL,以便您可以看到正确的限制已添加到 User 表中。
希望有帮助!
关于Spring - 整数属性的验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41749278/