美文网首页
"新增数据重复" 的全局处理(数据库索引)

"新增数据重复" 的全局处理(数据库索引)

作者: 墨色尘埃 | 来源:发表于2019-05-07 15:51 被阅读0次

    新增数据重复
    将重复的字段定义成索引,key为自定义(图中为"专业名称")。如果新增了一条重复的数据会抛出DuplicateKeyException异常,在log日志类捕获异常,并取出有用信息返回给前端。
    这样就避免了在代码里一条一条去查找。

    image.png
    catch (DuplicateKeyException throwable) {
                String currentTag = "E" + new Date().getTime();
                logger.error(sb.toString() + "\n" + "EXCEPTION{" + currentTag + "}:" + throwable.getMessage(), throwable);
                if (throwable.getMessage() != null) {
                    if (throwable.getMessage().contains("for key")) {
                        Matcher matcher = getDuplicateKeyPattern().matcher(throwable.getMessage());
                        if (matcher.find()) {
                            String dataDetail = matcher.group(1);
                            String entryKey = matcher.group(2);
                            return new ResponseObj<>(null, new RetCode("9990", entryKey + "存在重复数据,数据为"+dataDetail+ ",请修改后重试", currentTag));
                        }
                    }
                }
                return new ResponseObj<>(null, RetCode.FAILECHO);
            }
    
        Pattern duplicateKeyPattern = null;
    
        public Pattern getDuplicateKeyPattern() {
            if (duplicateKeyPattern == null) {
                String pattern = "Duplicate entry '(\\S+)' for key '(\\S+)'";
                duplicateKeyPattern = Pattern.compile(pattern);
            }
            return duplicateKeyPattern;
        }
    

    字段校验
    输入的信息过长超过了表里限制的长度,会报MysqlDataTruncation异常,不过这里就不使用上面“数据重复”的方式来返回信息给前端。Spring Boot使用校验框架validation校验
    【第十四篇: Spring Boot使用校验框架validation校验】
    springboot2.0-统一处理返回结果和异常情况

    相关文章

      网友评论

          本文标题:"新增数据重复" 的全局处理(数据库索引)

          本文链接:https://www.haomeiwen.com/subject/eauhoqtx.html