hibernate-validator校验工具类

validation-api-2.0.1.Final.jar
参考文档:http://docs.jboss.org/hibernate/validator/5.4/reference/en-US/html_single/

public class ValidatorUtils {
    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     *
     * @param object 待校验对象
     * @param groups 待校验的组
     * @throws BaseException 校验不通过,则报BaseException异常
     */
    public static void validateEntity(Object object, Class<?>... groups) throws BaseException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            ConstraintViolation<Object> constraint = (ConstraintViolation<Object>) constraintViolations.iterator()
                    .next();
            throw new BaseException(constraint.getMessage());
        }
    }
}

项目中应用

@HasPermisssion("monitor:job:add")
@OperLog(title = "定时任务",businessType = BusinussType.INSERT)
@PostMapping("save")
public R add(@RequestBody Job job) throws SchedulerException,TaskException{
	
	if(!CronUtils.isValid(job.getCronExpression())){
		return R.error("cron表达式不正确");
	}
	ValidatorUtils.validateEntity(job); //对传入的对象进行校验
	job.setCreateBy(getLoginName());
	return toAjax(jobService.insertJob(job));
}

你可能感兴趣的:(hibernate,java,后端)