MyBatis 插入返回自增主键

MyBatis从3.5开始在插入数据时会自动返回自增主键但之前版本和MyBatis Plus还不能,要想返回自增主键,可以采用以下两种方式:

  • 方式一
<insert id="insertReturnGeneratedKey" parameterType="dept" useGeneratedKeys="true" keyProperty="deptno">
    INSERT INTO db_test.dept
    <trim prefix="(" suffix=")" suffixOverrides=",">
        <if test="deptno!=null">deptno,</if>
        <if test="dname!=null">dname,</if>
        <if test="loc!=null">loc</if>
    </trim>
    VALUES
    <trim prefix="(" suffix=")" suffixOverrides=",">
        <if test="deptno!=null">#{deptno},</if>
        <if test="dname!=null">#{dname},</if>
        <if test="loc!=null">#{loc}</if>
    </trim>
</insert>
  • 方式二
<insert id="insertReturnGeneratedKey" parameterType="dept">
    INSERT INTO db_test.dept
    <trim prefix="(" suffix=")" suffixOverrides=",">
        <if test="deptno!=null">deptno,</if>
        <if test="dname!=null">dname,</if>
        <if test="loc!=null">loc</if>
    </trim>
    VALUES
    <trim prefix="(" suffix=")" suffixOverrides=",">
        <if test="deptno!=null">#{deptno},</if>
        <if test="dname!=null">#{dname},</if>
        <if test="loc!=null">#{loc}</if>
    </trim>
    <selectKey resultType="int" keyProperty="deptno" order="AFTER">
        SELECT LAST_INSERT_ID()
    </selectKey>
</insert>
发布了460 篇原创文章 · 获赞 812 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/lianghecai52171314/article/details/105595417
今日推荐