Myabtis中批量更新update多字段


在mybatis中批量更新多個字段

推薦使用如下操作:

方式1:在Dao層接口中:

void updateBatch(@Param("list")List<Student> list);

在對應的mapper文件中如下:

<update id="updateBatch" parameType="java.lang.List">
  update student
    <trim prefix="set" suffixOverrides=",">
       <trim prefix=" age = case " suffix="end,">
          <foreach collection="list" item="stu" index="index">
            <if test=" item.age != null and item.id != null">
              when id = #{item.id} then #{item.age}
            </if>
            <if test=" item.age == null and item.id != null">
              when id = #{item.id} then mydata_table.age //原始值
            </if>
          </foreach>
       </trim>
       <trim prefix=" name = case" suffix="end,">
          <foreach collection="list" item="stu" index="index">
            <if test=" item.name!= null and item.id != null">
              when id = #{item.id} then #{item.name}
            </if>
            <if test=" item.name == null and item.id != null">
              when id = #{item.id} then mydata_table.name //原始值
            </if>
          </foreach>
       </trim>
    </trim>
</update>

  上面的sql語句打印出來,應該是這個樣子的:

update student  
 
set  age = case
      when id = #{item.id} then #{item.status}//此處應該是<foreach>展開值  
     when id = #{item.id} then #{item.status}
      .... 
    end,
    
name = case
      when id = #{item.id} then #{item.status}
      ...
    end
where id in (?,?,?,?...);

<trim>屬性說明 

  1.prefix,suffix 表示在trim標簽包裹的部分的前面或者后面添加內容 
  2.如果同時有prefixOverrides,suffixOverrides 表示會用prefix,suffix覆蓋Overrides中的內容。 
  3.如果只有prefixOverrides,suffixOverrides 表示刪除開頭的或結尾的xxxOverides指定的內容 

方式2:在Dao層接口方法定義同上

  mapper文件如下:

<update id="updateBatch"  parameterType="java.util.List">  
    <foreach collection="list" item="item" index="index" open="" close="" separator=";">
        update student
        <set>
            name=#{item.name},
       age = #{item.age} </set> where id = #{item.id} </foreach> </update>

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM