mybatis中使用selectKey实现主键自增长

在实际开发中,插入数据时会遇到主键自增长的情况,这时可以通过<selectKey>标签实现,代码如下:

<insert id="id" parameterType="bean">
        <selectKey keyProperty="dataId" order="BEFORE" resultType="java.lang.Long">
            select nvl(id_num, 1) DATA_ID from (select max(DATA_ID) + 1 id_num from table)
        </selectKey>
        insert into LGD5_DATA(
        <if test="dataId != null and dataId != 0">DATA_ID,</if>
        <if test="dataLable != null and dataLable != ''">DATA_LABLE,</if>
        VERSION_NAME,
        VERSION
        ) values(
        <if test="dataId != null and dataId != 0">#{dataId},</if>
        <if test="dataLable != null and dataLable != ''">#{dataLable},</if>
        #{versionName},
        #{version}
        )
</insert>

其中,keyProperty对应model中主键名的属性名,order,BEFORE表示在插入语句之前执行selectKey中的内容,resultType表示主键类型

posted @ 2020-11-06 15:39  leviH  阅读(337)  评论(0)    收藏  举报