2
13693261870
2022-09-16 653761a31dfeb50dd3d007e892d69c90bf0cdafc
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
package com.landtool.lanbase.common.validator;
 
import java.util.Set;
 
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
 
import com.landtool.lanbase.common.exception.LanbaseException;
 
/**
 * 参考文档:http://docs.jboss.org/hibernate/validator/5.4/reference/en-US/html_single/
 * @author lanbase
 * @Description: TODO(hibernate-validator校验工具类)
 * @date 2017-6-23 15:07
 */
public class ValidatorUtils {
    private static Validator validator;
 
    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }
 
    /**
     * 校验对象
     * @param object        待校验对象
     * @param groups        待校验的组
     * @throws LanbaseException  校验不通过
     */
    public static void validateEntity(Object object, Class<?>... groups)
            throws LanbaseException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            StringBuilder msg = new StringBuilder();
            for(ConstraintViolation<Object> constraint:  constraintViolations){
                msg.append(constraint.getMessage()).append("<br>");
            }
            throw new LanbaseException(msg.toString());
        }
    }
}