org.dromara.hutool.extra.validation.ValidationUtil Maven / Gradle / Ivy
The newest version!
/*
* Copyright (c) 2023 looly([email protected])
* Hutool is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
package org.dromara.hutool.extra.validation;
import org.dromara.hutool.core.collection.CollUtil;
import jakarta.validation.*;
import java.util.Set;
/**
* java bean 校验工具类,此工具类基于validation-api(jakarta.validation-api)封装
*
* 在实际使用中,用户需引入validation-api的实现,如:hibernate-validator
* 注意:hibernate-validator还依赖了javax.el,需自行引入。
*
* @author chengqiang
* @since 5.5.0
*/
public class ValidationUtil {
/**
* 默认{@link Validator} 对象
*/
private static final Validator validator;
static {
try (final ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
validator = factory.getValidator();
}
}
/**
* 获取原生{@link Validator} 对象
*
* @return {@link Validator} 对象
*/
public static Validator getValidator() {
return validator;
}
/**
* 校验对象
*
* @param Bean类型
* @param bean bean
* @param groups 校验组
* @return {@link Set}
*/
public static Set> validate(final T bean, final Class>... groups) {
return validator.validate(bean, groups);
}
/**
* 校验对象,校验不通过,直接抛出给调用者
* 说明:如果Bean对象内部有非基本类型对象,需要把内部对象取出,进行手动多次调用,本方法
*
* @param object 待校验对象
* @param groups 待校验的组
* @throws ValidationException 校验不通过,则报 ValidationException 异常,调用者进行捕获,直接响应给前端用户
*/
public static void validateAndThrowFirst(final Object object, final Class>... groups)
throws ValidationException {
final Set> constraintViolations = validate(object, groups);
if (CollUtil.isNotEmpty(constraintViolations)) {
final ConstraintViolation