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