Java实现新增或修改时查询数据库是否重复,检查唯一
1 //Mapper层
2 int selectCountByCode(String code)
3
4 //mabatis层
5
6 resultType="java.lang.Integer">
7 select count(*)
8 from category
9 where code = #{code,jdbcType=VARCHAR}
10
11
12 //定义报错
13 // []已经存在
14 public static final Integer ERROR_CODE_ALREADY_EXIST = 4001001;
15 public static final String ERROR_MSG_ALREADY_EXIST = "[%s]=%s 已经存在";
16
17 //ServiceImpl
18 // 先验证 code 的唯一性(尽管数据库已经添加 unique 限制)
19 int countCode = hpCommodityCategoryMapper.selectCountByCode(code);
20 if (countCode > 0) {
21 // code 重复
22 LOGGER.error(String.format(ErrorCode.ERROR_MSG_ALREADY_EXIST, "code", code));
23 responseBody.setCode(ErrorCode.ERROR_CODE_ALREADY_EXIST);
24 responseBody.setMessage(String.format(ErrorCode.ERROR_MSG_ALREADY_EXIST, "code", code));
25 return responseBody;
26 }
原文链接:https://www.cnblogs.com/masterpick/p/13267708.html