Skip to content

Update spring-bean-validation.md #32

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 27, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 13 additions & 9 deletions docs/spring-bean-validation.md
Original file line number Diff line number Diff line change
Expand Up @@ -333,13 +333,17 @@ Validator validate
具体使用情况如下:

```java
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator()
PersonRequest personRequest = PersonRequest.builder().sex("Man22")
.classId("82938390").build();
Set<ConstraintViolation<PersonRequest>> violations = validator.validate(personRequest);
// 输出异常信息
violations.forEach(constraintViolation -> System.out.println(constraintViolation.getMessage()));
/**
* 手动校验对象
*/
@Test
public void check_person_manually() {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
PersonRequest personRequest = PersonRequest.builder().sex("Man22")
.classId("82938390").build();
Set<ConstraintViolation<PersonRequest>> violations = validator.validate(personRequest);
violations.forEach(constraintViolation -> System.out.println(constraintViolation.getMessage()));
}
```

Expand All @@ -350,7 +354,7 @@ sex 值不在可选范围
name 不能为空
```

## 自定以 Validator(实用)
## 自定义 Validator(实用)

如果自带的校验注解无法满足你的需求的话,你还可以自定义实现注解。

Expand Down Expand Up @@ -577,4 +581,4 @@ public class PersonService {
- `@NotNull`是 JSR 303 Bean 验证批注,它与数据库约束本身无关。
- `@Column(nullable = false)` : 是 JPA 声明列为非空的方法。

总结来说就是即前者用于验证,而后者则用于指示数据库创建表的时候对表的约束。
总结来说就是即前者用于验证,而后者则用于指示数据库创建表的时候对表的约束。