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>

 

猜你喜欢

转载自www.cnblogs.com/lxl-six/p/11766559.html