1. 程式人生 > >mybatis批量更新和插入

mybatis批量更新和插入

 

批量更新(1) 
<update id="updateBatch" parameterType="java.util.List">
  update supplier_unit_price
  <trim prefix="set" suffixOverrides=",">
    <trim prefix="UNIT = case" suffix="end,">
      <foreach collection="list" item="item" index="index">
        <if test="item.unit!=null">
          when id=#{item.id} then #{item.unit}
        </if>
      </foreach>
    </trim>

    <trim prefix="PRICE = case" suffix="end,">
      <foreach collection="list" item="item" index="index">
        <if test="item.price!=null">
          when id=#{item.id} then #{item.price}
        </if>
      </foreach>
    </trim>

    <trim prefix="MODIFIED_BY = case" suffix="end,">
      <foreach collection="list" item="item" index="index">
        <if test="item.modifiedBy!=null">
          when id=#{item.id} then #{item.modifiedBy}
        </if>
      </foreach>
    </trim>

    <trim prefix="MODIFICATION_TIME = case" suffix="end,">
      <foreach collection="list" item="item" index="index">
        <if test="item.modificationTime!=null">
          when id=#{item.id} then #{item.modificationTime}
        </if>
      </foreach>
    </trim>
  </trim>

  where 1 = 1
  <if test="list !=null and list.size >0">
    and (
    <foreach item="item" index="index" collection="list" open="(" separator="or" close=")">
      ID in #{item.id}
    </foreach>
    )
  </if>
</update>
批量更新(2)
<update id="updateImportInfo" parameterType="java.util.List">
  <foreach collection="list" item="item" index="index" separator=";"  open="begin" close=";end;">
    update supplier_unit_price
      <set>
        <if test="item.unit!=null">
        UNIT = #{item.unit},
      </if>
      <if test="item.price!=null">
        PRICE = #{item.price},
      </if>
      <if test="item.modifiedBy!=null">
        MODIFIED_BY = #{item.modifiedBy},
      </if>
      <if test="item.modificationTime!=null">
        MODIFICATION_TIME = #{item.modificationTime}
      </if>
    </set>
    WHERE ID = #{item.id}
 </foreach>
</update>
批量插入
<insert id ="insertBatch" parameterType="java.util.List" useGeneratedKeys="false">
  insert into supplier_unit_price
  (ID,SUPPLIER_ID, AREA_ID, TASK_TYPE_ID, BUSINESS_AREA_ID,PRICE,CREATION_TIME,MODIFIED_BY,MODIFICATION_TIME,DELETE_STATUS,FIRST_BIZ_ID,SECOND_BIZ_ID,UNIT)
  SELECT SEQ_S_UINT_PRICE.NEXTVAL,t.* from(
  <foreach collection="list" item="item" index="index" separator="union all">
    SELECT
    #{item.supplierId},
    #{item.areaId},
    #{item.taskTypeId},
    #{item.businessAreaId},
    #{item.price},
    #{item.creationTime,jdbcType=TIMESTAMP},
    #{item.modifiedBy,jdbcType=VARCHAR},
    #{item.modificationTime,jdbcType=TIMESTAMP},
    #{item.deleteStatus},
    #{item.firstBizId},
    #{item.secondBizId},
    #{item.unit}
    FROM DUAL
  </foreach>
  )t
</insert>