You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
package com.utils ;
// 导入必要的Java工具类
import java.util.Set ;
// 导入验证相关的类
import javax.validation.ConstraintViolation ;
import javax.validation.Validation ;
import javax.validation.Validator ;
// 导入自定义异常类
import com.entity.EIException ;
// 数据校验工具类, 基于hibernate-validator实现
public class ValidatorUtils {
// 静态验证器实例
private static Validator validator ;
// 静态初始化块,初始化验证器
static {
// 获取默认的验证器工厂并创建验证器实例
validator = Validation . buildDefaultValidatorFactory ( ) . getValidator ( ) ;
}
// 校验对象方法
// object: 需要校验的对象
// groups: 可选的校验组
// 抛出EIException当校验失败时
public static void validateEntity ( Object object , Class < ? > . . . groups )
throws EIException {
// 执行校验并获取校验结果集合
Set < ConstraintViolation < Object > > constraintViolations = validator . validate ( object , groups ) ;
// 检查是否有校验错误
if ( ! constraintViolations . isEmpty ( ) ) {
// 获取第一个校验错误
ConstraintViolation < Object > constraint = ( ConstraintViolation < Object > ) constraintViolations . iterator ( ) . next ( ) ;
// 抛出包含错误信息的异常
throw new EIException ( constraint . getMessage ( ) ) ;
}
}
}