zhaowenxuan
2025-02-06 06c12d2b42c343798d9476be66031b48967df639
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.ltkj.tduck.utils;
 
 
 
 
import com.ltkj.common.exception.base.BaseException;
 
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
 
/**
 * @description: hibernate 校验工具类
 * 不通过注解使用 通过工具类返回自定义结果
 * @author: smalljop
 * @create: 2018-10-12 10:20
 **/
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()) {
            StringBuilder msg = new StringBuilder();
            for (ConstraintViolation<Object> constraint : constraintViolations) {
                msg.append(constraint.getMessage());
            }
            throw new BaseException(msg.toString());
        }
    }
 
    public static void validateEntity(Object object)
            throws BaseException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object);
        if (!constraintViolations.isEmpty()) {
            StringBuilder msg = new StringBuilder();
            for (ConstraintViolation<Object> constraint : constraintViolations) {
                msg.append(constraint.getMessage()).append("<br>");
            }
            throw new BaseException(msg.toString());
        }
    }
}