在实际的应用场景中,经常会遇到插入一条新记录后就对它进行相关操作。例如,处理其关系,因此要用到新记录的主键。为了简化操作Mybatis可以在插入的同时获取记录的主键。
有两种形式如下:
<!--返回主键 :我们的主键需要设置自动递增 -->
<insert id="insertGetId" parameterType="com.qcby.entity.User">
<selectKey keyProperty="id" resultType="int" order="AFTER">
SELECT LAST_INSERT_ID()
</selectKey>
insert into user(username,birthday,sex,address)
values(#{username},#{birthday},#{sex},#{address})
</insert>
<!--回填主键:useGeneratedKeys="true" keyProperty="id" -->
<insert id="insertTwo" parameterType="com.mbyte.easy.admin.entity.Student"
useGeneratedKeys="true" keyProperty="id">
insert into student (name, img, sex, create_time)
values (
#{student.name,jdbcType=VARCHAR},
#{student.img,jdbcType=VARCHAR},
#{student.sex,jdbcType=INTEGER},
#{student.createTime,jdbcType=TIMESTAMP}
)
</insert>
第一种使用<selectKey>并调用SQL内置的函数LAST_INSERT_ID(),第二种在<insert>中给参数useGeneratedKeys赋值为真。值的注意的是,两种方法都是将查询的的id匹配给具体对象的id属性而不是方法的返回值。