数据库主键为字母编号+数字,并且需要自增

业务需求:

  • 数据库主键为字母+数字
  • 主键数字自增添加

数据库结构
在这里插入图片描述

mybatis部分代码

    <select id="getId" resultType="java.lang.String">
    SELECT
    IFNULL(( select tube_id  from tp_tube
    where tube_id=(select tube_id from tp_tube order by tube_id desc limit 1)),'TPBE000000')
    </select>

指明条件:根据tube_id逆序查找 如果表中数据为空的话,利用MySQL IFNULL函数返回TPBE000000(自定义字段)

设置主键工具类

public class SetIdUtil {

    public static String setId(String id) {
        //截取头部字母编号
        String head = id.substring(0, id.indexOf("0"));
        //截取尾部数字
        String tail = id.substring(head.length(), id.length());
        //尾部数字 +1
        int num = Integer.valueOf(tail) + 1;
        //填充 0
        String s = null;
        for (int i = 0; i <= id.length(); i++) {
            s += "0";
        }
        //合并字符串
        s = s + num;
        s = s.substring(s.length() - tail.length(), s.length());
        return head + s;
    }

}

将+1的主键ID插入数据库

    @Override
    public ResultVO insertTube(TpTubeForm tubeForm) {
        TpTube tpTube = new TpTube();
        BeanUtils.copyProperties(tubeForm, tpTube);
        tpTube.setTubeId(SetIdUtil.setId(tubeMapper.getId()));
        if (insert(tpTube)) {
            return ResultVOUtil.success(tpTube);
        }
        return ResultVOUtil.error(ResultEnum.SERVER_ERROR);
    }

结果演示
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章