结果集对象
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ValidationResult {
private boolean success;
private Map<String,String> errorMsg;
}
工具类:
package com.hbsi.util;
import org.springframework.util.CollectionUtils;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class ValidationUtils<T> {
private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
public static <T> ValidationResult validateEntity(T obj){
ValidationResult result = new ValidationResult();
Set<ConstraintViolation<T>> violationSet = validator.validate(obj, Default.class);
if(!CollectionUtils.isEmpty(violationSet)){
result.setSuccess(false);
Map<String,String> errMsg = new HashMap<>();
violationSet.forEach(e->errMsg.put(e.getPropertyPath().toString(),e.getMessage()));
result.setErrorMsg(errMsg);
}else
result.setSuccess(true);
return result;
}
public static <T> ValidationResult validateProperty(T obj,String propertyName){
ValidationResult result = new ValidationResult();
Set<ConstraintViolation<T>> violationSet = validator.validateProperty(obj, propertyName, Default.class);
if(!CollectionUtils.isEmpty(violationSet)){
result.setSuccess(false);
Map<String,String> errMsg = new HashMap<>();
violationSet.forEach(e->errMsg.put(e.getPropertyPath().toString(),e.getMessage()));
result.setErrorMsg(errMsg);
}else
result.setSuccess(true);
return result;
}
}