Hibernate Validation与Spring整合各注解的用法Demo

时间:2023-03-09 16:02:48
Hibernate Validation与Spring整合各注解的用法Demo
  1. 转自:https://www.aliyun.com/jiaocheng/1315650.html
  1. <dependency>
  2. <groupId>org.hibernate</groupId>
  3. <artifactId>hibernate-validator</artifactId>
  4. <version>5.1.1.Final</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>javax.el</groupId>
  8. <artifactId>javax.el-api</artifactId>
  9. <version>2.2.4</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.glassfish.web</groupId>
  13. <artifactId>javax.el</artifactId>
  14. <version>2.2.4</version>
  15. </dependency>
与spring整合的配置:

Hibernate Validation与Spring整合各注解的用法Demo

Hibernate Validation与Spring整合各注解的用法Demo
  1. <!-- 配置 JSR303 Bean Validator 定义 -->
  2. <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

实体类属性上加注解约束
Hibernate Validation与Spring整合各注解的用法DemoHibernate Validation与Spring整合各注解的用法Demo
  1. @NotNull(message="书籍的姓名不能为空!")
  2. public String getBookName() {
  3. return bookName;
  4. }
  1. /**
  2. * 服务端参数有效性验证
  3. * @param object 验证的实体对象
  4. * @param groups 验证组
  5. * @return 验证成功:返回true;严重失败:将错误信息添加到 flash message 中
  6. */
  7. @SuppressWarnings("rawtypes")
  8. public static void validateWithException(Validator validator, Object object, Class<?>... groups)
  9. throws ConstraintViolationException {
  10. Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
  11. if (!constraintViolations.isEmpty()) {
  12. StringBuffer sb=new StringBuffer();
  13. for (ConstraintViolation constraintViolation : constraintViolations) {
  14. sb.append(constraintViolation.getMessage());
  15. }
  16. throw new RuntimeException(sb.toString());
  17. //throw new ConstraintViolationException(constraintViolations);
  18. }
  19. }
  20. 测试类方法:
  21. @Test
  22. public void testSaveBook(){
  23. Book book=new Book();
  24. book.setBookPrice(100);
  25. book.setBookStock(10);
  26. //        book.setBookName("norelax");
  27. validateWithException(validator, book);
  28. System.out.println(buyService.saveBook(10, null, 10));
  29. }
测试结果:
java.lang.RuntimeException: 书籍的姓名不能为空!
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:232)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:175)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:670)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
  • Bean Validation 中内置的 constraint(约束)
  • @Null   被注释的元素必须为 null
  • @NotNull    被注释的元素必须不为 null
  • @AssertTrue     被注释的元素必须为 true
  • @AssertFalse    被注释的元素必须为 false
  • @Min(value)     被注释的元素必须是一个数字,其值必须大于等于指定的最小值
  • @Max(value)     被注释的元素必须是一个数字,其值必须小于等于指定的最大值
  • @DecimalMin(value)  被注释的元素必须是一个数字,其值必须大于等于指定的最小值
  • @DecimalMax(value)  被注释的元素必须是一个数字,其值必须小于等于指定的最大值
  • @Size(max=, min=)   被注释的元素的大小必须在指定的范围内
  • @Digits (integer, fraction)     被注释的元素必须是一个数字,其值必须在可接受的范围内
  • @Past   被注释的元素必须是一个过去的日期
  • @Future     被注释的元素必须是一个将来的日期
  • @Pattern(regex=,flag=)  被注释的元素必须符合指定的正则表达式
  • Hibernate Validator 附加的 constraint
  • @NotBlank(message =)   验证字符串非null,且长度必须大于0
  • @Email  被注释的元素必须是电子邮箱地址
  • @Length(min=,max=)  被注释的字符串的大小必须在指定的范围内
  • @NotEmpty   被注释的字符串的必须非空
  • @Range(min=,max=,message=)  被注释的元素必须在合适的范围内