Java实现新增或修改时查询数据库是否重复,检查唯一


声明
1)该文章整理自网上的大牛和专家无私奉献的资料,具体引用的资料请看参考文献。
2)本文仅供学术交流,非商用。如果某部分不小心侵犯了大家的利益,还望海涵,并联系博主删除。
3)博主才疏学浅,文中如有不当之处,请各位指出,共同进步,谢谢。
4)此属于第一版本,若有错误,还需继续修正与增删。还望大家多多指点。大家都共享一点点,一起为祖国科研的推进添砖加瓦。

1 //Mapper层
 2     int selectCountByCode(String code)
 3     
 4 //mabatis层
 5 <select id="selectCountByCode" parameterType="java.lang.String"
 6     resultType="java.lang.Integer">
 7     select count(*)
 8     from category
 9     where code = #{code,jdbcType=VARCHAR}
10 </select>
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