mybatis插入数据时,自动获取主键的自增id

首先int i = userMapper.insertSelective(user),这里返回的并不是主键自增id,而是成功插入的条数。如果想获取主键自增id,除了插入记录之后再查询之外,也可以使用mybatis提供的两种方式:
一是mybatis自动生成的sql语句:

  <insert id="insertSelective" parameterType="cn.tencent.eee.aaa.dao.model.User">
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into user
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="name != null">
        name,
      </if>
      <if test="createBy != null">
        create_by,
      </if>
      <if test="updateBy != null">
        update_by,
      </if>
      <if test="sysCtime != null">
        sys_ctime,
      </if>
      <if test="sysUtime != null">
        sys_utime,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="name != null">
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="createBy != null">
        #{createBy,jdbcType=VARCHAR},
      </if>
      <if test="updateBy != null">
        #{updateBy,jdbcType=VARCHAR},
      </if>
      <if test="sysCtime != null">
        #{sysCtime,jdbcType=TIMESTAMP},
      </if>
      <if test="sysUtime != null">
        #{sysUtime,jdbcType=TIMESTAMP},
      </if>
    </trim>
  </insert>

二是在insert标签加属性,是否使用 useGeneratedKeys 开关为true,keyProperty对应的就是要返回的字段名称:

  <insert id="insertSelective" parameterType="cn.tencent.eee.aaa.dao.model.User" useGeneratedKeys="true" keyProperty="id">
  </insert>

注意:
1.通过以上两种方式获取自增id时,会直接赋值到领域模型的实体id中;

Integer i = user.getId;// i == null
if(userMapper.insertSelective(user) > 0){//如果插入成功
   i = user.getId;//i为主键自增id
}

2.insert标签里如果有多条insert语句,那么返回的则是最后一条insert语句的自增id。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值