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>