mybatis一个方法执行多条sql_Java学习之——MyBatis逆向工程执行方法的问题

64ee4595d910b3b8773580b2cafe2176.png

861f9e75b5cd76b9d2e1a6b42e31850c.png

在使用MyBatis时,通常使用逆向工程工具生成一套接口和xml映射文件用于简单的单表操作,而其中有两个比较常用的接口方法:

一个是updateByExample,一个是 updateByExampleSelective 。

它们的作用是对数据库进行更新操作。

通过查看逆向工程的xml映射文件可以发现,这两个方法的区别是:

updateByExample的代码为:

 <update id="updateByExample" parameterType="map">
    update tb_item
    set id = #{record.id,jdbcType=BIGINT},
      title = #{record.title,jdbcType=VARCHAR},
      sell_point = #{record.sellPoint,jdbcType=VARCHAR},
      price = #{record.price,jdbcType=BIGINT},
      num = #{record.num,jdbcType=INTEGER},
      barcode = #{record.barcode,jdbcType=VARCHAR},
      image = #{record.image,jdbcType=VARCHAR},
      cid = #{record.cid,jdbcType=BIGINT},
      status = #{record.status,jdbcType=TINYINT},
      created = #{record.created,jdbcType=TIMESTAMP},
      updated = #{record.updated,jdbcType=TIMESTAMP}
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>

可以看出:

updateByExample需要将表的条件全部给出,比如一个表中有三个字段,就必须给三个字段给它,不给会设为null


updateByExampleSelective的代码为:

<update id="updateByExampleSelective" parameterType="map">
    update tb_item
    <set>
      <if test="record.id != null">
        id = #{record.id,jdbcType=BIGINT},
      </if>
      <if test="record.title != null">
        title = #{record.title,jdbcType=VARCHAR},
      </if>
      <if test="record.sellPoint != null">
        sell_point = #{record.sellPoint,jdbcType=VARCHAR},
      </if>
      <if test="record.price != null">
        price = #{record.price,jdbcType=BIGINT},
      </if>
      <if test="record.num != null">
        num = #{record.num,jdbcType=INTEGER},
      </if>
      <if test="record.barcode != null">
        barcode = #{record.barcode,jdbcType=VARCHAR},
      </if>
      <if test="record.image != null">
        image = #{record.image,jdbcType=VARCHAR},
      </if>
      <if test="record.cid != null">
        cid = #{record.cid,jdbcType=BIGINT},
      </if>
      <if test="record.status != null">
        status = #{record.status,jdbcType=TINYINT},
      </if>
      <if test="record.created != null">
        created = #{record.created,jdbcType=TIMESTAMP},
      </if>
      <if test="record.updated != null">
        updated = #{record.updated,jdbcType=TIMESTAMP},
      </if>
    </set>
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>

而updateByExampleSelective不同,当某一实体类的属性为null时,mybatis会使用动态sql过滤掉,不更新该字段

总结:虽然MyBatis逆向工程很好用,可以帮我们自动生成代码,但还是使用的时候需要注意一下细节。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值