编辑
2024-06-01
后端
00
请注意,本文编写于 253 天前,最后修改于 252 天前,其中某些信息可能已经过时。

在后端开发中,对于键唯一值的判断很常见,但是每判断一个键就要几行if判断,很啰嗦,怎么才能让我们开发的效率更高呢。

(你肯定也写过像以下这种代码)

重复的判断浪费了太多时间,使用其实在数据库中使用unique进行约束即可

sql
create table sys_user ( id mediumtext null, username varchar(256) null, password varchar(128) null, nickname varchar(256) null, role tinyint default 0 not null comment '角色 ''用户|管理员'' 0 1', phone varchar(20) null, email varchar(128) null, create_time datetime null, deleted tinyint default 0 not null comment '逻辑删除', constraint sys_user_pk unique (username), constraint sys_user_pk2 unique (phone), constraint sys_user_pk3 unique (email) ) row_format = DYNAMIC;

当然如果插入报错,报错信息可能是这样的

### Error updating database. Cause: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'admin' for key 'sys_user.sys_user_pk' ### The error may exist in cn/pepedd/mapper/UserMapper.java (best guess) ### The error may involve cn.pepedd.mapper.UserMapper.insert-Inline ### The error occurred while setting parameters ### SQL: INSERT INTO sys_user ( id, username, nickname, password, role, email, create_time ) VALUES ( ?, ?, ?, ?, ?, ?, ? ) ### Cause: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'admin' for key 'sys_user.sys_user_pk' ; Duplicate entry 'admin' for key 'sys_user.sys_user_pk'; nested exception is java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'admin' for key 'sys_user.sys_user_pk'

不能直接在接口显示,于是我们使用异常处理器处理这个错误即可

  • 不返回重复的键名
java
/** * 处理键重复异常 */ @ExceptionHandler(DuplicateKeyException.class) public R handleDuplicateKeyException(DuplicateKeyException e) { return R.error(ErrorCode.PARAMS_ERROR, "数据重复,请检查后提交"); }
  • 返回重复的键名
java
/** * 处理键重复异常 */ @ExceptionHandler(DuplicateKeyException.class) public R handleDuplicateKeyException(DuplicateKeyException e) { String errorMessage = e.getMessage(); String duplicateEntry = null; // 从错误消息中提取字段名 Pattern pattern = Pattern.compile("Duplicate entry '(.*?)' for key '.*'"); Matcher matcher = pattern.matcher(errorMessage); if (matcher.find()) { duplicateEntry = matcher.group(1); } String message = "数据重复,请检查后提交"; if (duplicateEntry != null) { message += "。重复的值是:" + duplicateEntry; } return R.error(ErrorCode.PARAMS_ERROR, message); }

就像这样

如果对你有用的话,可以打赏哦
打赏
ali pay
wechat pay

本文作者:peepdd864

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!