validator校验工具类

import io.renren.common.exception.RRException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * hibernate-validator校验工具类
 *
 * 参考文档:http://docs.jboss.org/hibernate/validator/5.4/reference/en-US/html_single/
 *
 * @author Mark [email protected]
 */
public class ValidatorUtils {
    private static Validator validator;

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

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

使用

/**
     * 保存配置
     */
    @SysLog("保存配置")
    @RequestMapping("/save")
    @RequiresPermissions("sys:config:save")
    public R save(@RequestBody SysConfigEntity config){
        ValidatorUtils.validateEntity(config);

        sysConfigService.saveConfig(config);
        
        return R.ok();
    }

实体类

/**
 * 系统配置信息
 *
 * @author Mark [email protected]
 */
@Data
@TableName("sys_config")
public class SysConfigEntity {
    @TableId
    private Long id;
    @NotBlank(message="参数名不能为空")
    private String paramKey;
    @NotBlank(message="参数值不能为空")
    private String paramValue;
    private String remark;

}

你可能感兴趣的:(validator校验工具类)