mybatis解决主键自增问题
最近,小编刚实习,说一下在工作中遇到的问题,其中就有mybatis解决主键自增的问题
在oracle数据库中
1、创建序列
在oracle中没有像mysql一样可以使用 AUTO_INCREMENT
id int(11) NOT NULL AUTO_INCREMENT
所以需要用到序列,首先在数据库中新建序列
创建序列
CREATE SEQUENCE DHDC_PS_ID_SEQ
INCREMENT BY 1 - 每次加几个
START WITH 1 - 从1开始计数
NOMAXvalue - 不设置最大值
NOCYCLE - 一直累加,不循环
CACHE 10;
2、在mybatis中写上
<insert id="InsertBackLog" parameterType="com.dhdc.dto.BackLogOutDto">
<selectKey resultType="java.lang.String" order="BEFORE" keyProperty="id">
SELECT DHDC_PS_ID_SEQ.nextval as id FROM DUAL
</selectKey>
INSERT INTO SELF_D1_MESSAGE_BOARD
(id,
MESSAGE_TYPE,
READ_STS,
<if test="messageTitle!=null and messageTitle!=''">
MESSAGE_TITLE,
</if>
<if test="messageContent!=null and messageContent!=''">
MESSAGE_CONTENT,
</if>
SEND_DATE, USER_ID, USER_TYPE)
VALUES(
#{id},
#{messageType},
#{readSts},
<if test="messageTitle!=null and messageTitle!=''">
#{messageTitle},
</if>
<if test="messageContent!=null and messageContent!=''">
#{messageContent},
</if>
sysdate,
#{userId},
#{userType})
</insert>
当表撤销时,记得把序列删除
DROP SEQUENCE SEQ_DHDC_PUBLIC_ID
2、使用oracle函数解决主键自增问题
select nvl(max(id)+1,1) from SELF_D1_MESSAGE_BOARD
<insert id="InsertBackLog" parameterType="com.dhdc.dto.BackLogOutDto">
INSERT INTO SELF_D1_MESSAGE_BOARD
(id,
MESSAGE_TYPE,
READ_STS,
<if test="messageTitle!=null and messageTitle!=''">
MESSAGE_TITLE,
</if>
<if test="messageContent!=null and messageContent!=''">
MESSAGE_CONTENT,
</if>
SEND_DATE, USER_ID, USER_TYPE)
VALUES(
(select nvl(max(id)+1,1) from SELF_D1_MESSAGE_BOARD),
#{messageType},
#{readSts},
<if test="messageTitle!=null and messageTitle!=''">
#{messageTitle},
</if>
<if test="messageContent!=null and messageContent!=''">
#{messageContent},
</if>
sysdate,
#{userId},
#{userType})
</insert>
nvl(str1,str2)函数 : 当str1为空时,用str2的值,不为空则用str1
这是用来解决表第一次插入时,表中没有id 的情况
2、在mysql中
使用
useGeneratedKeys=“true” keyProperty=“id” keyColumn=“id”
<insert id="insertContentDataManage"
parameterType="com.function1.ContentDataManageEntity"
useGeneratedKeys="true" keyProperty="id" keyColumn="id">
insert into content_data_manage(
channel_id,
data_title,
data_modal_id,
create_user_id,
create_user_name,
create_time
)values (
#{bean.channelId},
#{bean.dataTitle},
#{bean.dataModalId},
#{bean.createUserId},
#{bean.createUserName},
now()
)
</insert>
各位看官,如果有帮助到你,麻烦点个赞赞哦