mirror of
https://gitee.com/bookshelfplus/bookshelfplus
synced 2025-10-07 00:15:15 +08:00
添加查询书籍;BookDO映射文件更新;DOMapper添加@Repository注解;添加自定义业务异常处理;添加Validation验证
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
package plus.bookshelf.Common.Validator;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class ValidationResult {
|
||||
// 校验结果是否有错
|
||||
private boolean hasErrors = false;
|
||||
|
||||
// 存放错误信息的Map
|
||||
private Map<String, String> errMsgMap = new HashMap<>();
|
||||
|
||||
// 实现通用的通过格式化字符串信息获取错误结果的msg方法
|
||||
public String getErrMsg() {
|
||||
return StringUtils.join(errMsgMap.values().toArray(), ",");
|
||||
}
|
||||
|
||||
public boolean isHasErrors() {
|
||||
return hasErrors;
|
||||
}
|
||||
|
||||
public void setHasErrors(boolean hasErrors) {
|
||||
this.hasErrors = hasErrors;
|
||||
}
|
||||
|
||||
public Map<String, String> getErrMsgMap() {
|
||||
return errMsgMap;
|
||||
}
|
||||
|
||||
public void setErrMsgMap(Map<String, String> errMsgMap) {
|
||||
this.errMsgMap = errMsgMap;
|
||||
}
|
||||
}
|
@@ -0,0 +1,37 @@
|
||||
package plus.bookshelf.Common.Validator;
|
||||
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.Validator;
|
||||
import java.util.Set;
|
||||
|
||||
@Component
|
||||
public class ValidatorImpl implements InitializingBean {
|
||||
|
||||
private Validator validator;
|
||||
|
||||
// 实现校验方法并返回校验结果
|
||||
public ValidationResult validate(Object bean) {
|
||||
ValidationResult result = new ValidationResult();
|
||||
Set<ConstraintViolation<Object>> constraintViolationSet = validator.validate(bean);
|
||||
if (constraintViolationSet.size() > 0) {
|
||||
// 有错误
|
||||
result.setHasErrors(true);
|
||||
constraintViolationSet.forEach(constraintViolation -> {
|
||||
String errMsg = constraintViolation.getMessage();
|
||||
String propertyName = constraintViolation.getPropertyPath().toString();
|
||||
result.getErrMsgMap().put(propertyName, errMsg);
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
// 将Hibernate Validator通过工厂的初始化方式使其实例化
|
||||
this.validator = (Validator) Validation.buildDefaultValidatorFactory().getValidator();
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user