内容目录
ValidateUtil
package com.uinfor.mes.base.utils;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.Validator;
import java.util.Set;
/**
* 校验工具类
*
* 2023/4/18
* @author wintersakura
*/
public class ValidateUtil {
private static final Validator VALIDATOR =
Validation.buildDefaultValidatorFactory().getValidator();
/**
* 校验实体类
*/
public static <T> void validate(T t) {
Set<ConstraintViolation<T>> constraintViolations = VALIDATOR.validate(t);
if (constraintViolations.size() > 0) {
StringBuilder validateError = new StringBuilder();
for (ConstraintViolation<T> constraintViolation : constraintViolations) {
validateError.append(constraintViolation.getMessage()).append(";");
}
throw new ValidationException(validateError.toString());
}
}
/**
* 通过组来校验实体类
*/
public static <T> void validate(T t, Class<?>... groups) {
Set<ConstraintViolation<T>> constraintViolations = VALIDATOR.validate(t, groups);
if (constraintViolations.size() > 0) {
StringBuilder validateError = new StringBuilder();
for (ConstraintViolation<T> constraintViolation : constraintViolations) {
validateError.append(constraintViolation.getMessage()).append(";");
}
throw new ValidationException(validateError.toString());
}
}
}
用法
/**
* 统一自定义校验
*/
private <T> void validate(T obj) {
try {
ValidateUtil.validate(obj);
} catch (Exception e) {
throw new ServiceException(e.getMessage());
}
}