業務需求:
- 數據庫主鍵爲字母+數字
- 主鍵數字自增添加
數據庫結構
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);
}
結果演示