mybatis:updatebyexample与updateByExampleSelective

  MyBatis,通常逆向工程工具生成接口和xml映射文件用于简单的单表操作。

  有两个方法: updateByExample 和 updateByExampleSelective  ,作用是对数据库进行更新操作。(insert和insertSelective也一球样!)

注意:1,区别在于后者比前者多了动态标签<if test="xxx != null">的判断,有空值,不进行插入操作。

   2,updateByExampleSelective可以不按主键更新,条件中可以不包含主键;updateByExample条件中必须包含主键

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>

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>

 UpdateByExampleSelectivce使用:

  ProLogExample example = new ProLogExample();
  example.createCriteria().andNameEqualTo(xiaoming.getName());
  proLogMapper.updateByExampleSelective(xiaoming, example);

posted @ 2019-11-20 09:49  404UnknownCoder  阅读(2381)  评论(0)    收藏  举报