hibernate分组校验实践

参考:
https://www.cnblogs.com/mr-yang-localhost/p/7812038.html

  1. ValidatorConfiguration配置类
import org.hibernate.validator.HibernateValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

/**
 * 描述:validator配置
 *
 * @author xuery
 * @date 2018/12/5
 */
@Configuration
public class ValidatorConfiguration {

    @Bean
    public Validator validator(){
        ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class )
                .configure()
                .addProperty( "hibernate.validator.fail_fast", "true" ) //true设置为快速失败模式,一个校验不通过则不再继续
                .buildValidatorFactory();
        Validator validator = validatorFactory.getValidator();

        return validator;
    }

    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        MethodValidationPostProcessor postProcessor = new MethodValidationPostProcessor();
        /**设置validator模式为快速失败返回*/
        postProcessor.setValidator(validator());
        return postProcessor;
    }
}
  1. GlobalExceptionHandler校验异常捕获handler
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.Set;

/**
 * 描述:捕获MethodValidationPostProcessor校验不通过时抛出的异常,并抛出给前端
 *  @ControllerAdvice+ @ExceptionHandler
 * @author xuery
 * @date 2018/12/5
 */
@ControllerAdvice
@Component
public class GlobalExceptionHandler {

    @ExceptionHandler
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String handle(ValidationException exception) {
        if(exception instanceof ConstraintViolationException){
            ConstraintViolationException exs = (ConstraintViolationException) exception;

            Set> violations = exs.getConstraintViolations();
            for (ConstraintViolation item : violations) {
                /**打印验证不通过的信息*/
                System.out.println(item.getMessage());
            }
        }
        return "bad request, " ;
    }
}

  1. 定义不同分组:InsertGroup和UpdateGroup组
public interface InsertGroup {
}

public interface UpdateGroup {
}
  1. 指定插入、更新校验组顺序
@GroupSequence({InsertGroup.class, Default.class})
public interface InsertOrder {
}

@GroupSequence({UpdateGroup.class, Default.class})
public interface UpdateOrder {

}
  1. 开始校验
  • 需要校验的staff类
@Data
public class Staff {

    @NotNull
    @Range(min = 1, max = Integer.MAX_VALUE, message = "必须大于0", groups = {Default.class})
    private Integer id;

    /**
     * InsertGroup组才会校验
     */
    @NotBlank(message = "staffName不能为空",groups = {InsertGroup.class})
    private String staffName;

    /**
     * UpdateGroup组才会校验
     */
    @NotBlank(message = "updateValue不能为空",groups = {UpdateGroup.class})
    private String updateValue;
}
  • 校验service及实现类
public interface StaffService {

    int insertStaff(Staff staff);

    int updateStaff(Staff staff);
}

@Service
public class StaffServiceImpl implements  StaffService {

    @Autowired
    private Validator validator;

    /**
     * 注意这里只是做演示,实际场景需要返回错误的信息
     * @param staff
     * @return
     */
    @Override
    public int insertStaff(Staff staff) {

        Set> validate =  validator.validate(staff, InsertOrder.class);
        if(CollectionUtils.isNotEmpty(validate)){
            for(ConstraintViolation constraintViolation : validate){
                System.out.println(constraintViolation.getMessage());
            }
            return -1;
        }
        return 1;
    }

    /**
     * 注意这里只是做演示,实际场景需要返回错误的信息
     * @param staff
     * @return
     */
    @Override
    public int updateStaff(Staff staff) {
        Set> validate =  validator.validate(staff, UpdateOrder.class);
        if(CollectionUtils.isNotEmpty(validate)){
            for(ConstraintViolation constraintViolation : validate){
                System.out.println(constraintViolation.getMessage());
            }
            return -1;
        }
        return 1;
    }
}
  • 测试类
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MySpringBootApplication.class)
public class StaffServiceTest {


    @Autowired
    private StaffService staffService;

    @Test
    public void testInsertStaff(){
        Staff staff = new Staff();
        staff.setId(12);
        staff.setStaffName("xuery"); //注释掉会打印错误信息
        staffService.insertStaff(staff);
    }

    @Test
    public void testUpdateStaff(){
        Staff staff = new Staff();
        staff.setId(12);
        staff.setUpdateValue("1234"); //注释掉会打印错误信息
        staffService.updateStaff(staff);
    }
}

你可能感兴趣的:(hibernate分组校验实践)