Mybatis回填主键

在实际的应用场景中,经常会遇到插入一条新记录后就对它进行相关操作。例如,处理其关系,因此要用到新记录的主键。为了简化操作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属性而不是方法的返回值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值