Starting from 3.5, MyBatis will automatically return to the auto-increment primary key when inserting data, but the previous version and MyBatis Plus are not yet.
- method one
<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>
- Method two
<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>