使用Mybatis返回插入数据的自增主键

18 篇文章 0 订阅

首先在Mybatis的xml加入 useGeneratedKeys="true" keyProperty="userId"两条属性

useGeneratedKeys默认是false,当设置为true时,会返回当前插入数据的主键值到入参的参数中;

keyProperty:指定主键名称

具体使用如下:

<insert id="insertSelective" parameterType="com.tymk.front.model.hebi.HebiChangedLog" useGeneratedKeys="true" keyProperty="id">
    insert into hebi_changed_log
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="userId != null">
        user_id,
      </if>
      <if test="operType != null">
        oper_type,
      </if>
      <if test="changedTime != null">
        changed_time,
      </if>
      <if test="changedAmount != null">
        changed_amount,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=BIGINT},
      </if>
      <if test="userId != null">
        #{userId,jdbcType=BIGINT},
      </if>
      <if test="operType != null">
        #{operType,jdbcType=INTEGER},
      </if>
      <if test="changedTime != null">
        #{changedTime,jdbcType=TIMESTAMP},
      </if>
      <if test="changedAmount != null">
        #{changedAmount,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>

然后我们的插入语句中的原有值中就会增加id的值,然后获取id即可。

HebiChangedLog hebiChangedLogPara = new HebiChangedLog();
hebiChangedLogPara.setChangedAmount(hebiPackageInfo.getExchangePrice());
hebiChangedLogPara.setChangedTime(new Date());
hebiChangedLogPara.setOperType(12);
hebiChangedLogPara.setUserId(userId);
hebiChangedLogMapper.insertSelective(hebiChangedLogPara);

//我们在这里就能获取到id了
hebiChangedLogPara.getId();

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值