Mybatis 批量更新多个字段 | Eddie'Blog
Mybatis 批量更新多个字段

Mybatis 批量更新多个字段

eddie 669 2020-05-12

批量更新多个字段

描述

有两种方式,取其中一种贴代码吧, 不贴sql, 太少 就几个字段的表!

单元测试方法

@Test
public void updateUserbath(){
	User u1 = User.builder()
			.id("1")
			.name("eddie1")
			.age(19)
			.email("eddie1@qq.com")
			.build();

	User u2 = User.builder()
			.id("2")
			.name("dante1")
			.age(20)
			.email("dante1@qq.com")
			.build();

	List<User> users = Arrays.asList(u1, u2);

	userMapper.updateUserbath(users);
}

dao

void updateUserbath(List<User> users );

xml

    <update id="updateUserbath" parameterType="java.util.List">
        update mp_user
        <trim prefix="set" suffixOverrides=",">

            <trim prefix="name=case" suffix="end,">
                <foreach collection="list" item="item" index="index">
                    when id = #{item.id} then #{item.name}
                </foreach>
            </trim>

            <trim prefix="age=case" suffix="end,">
                <foreach collection="list" item="item" index="index">
                    when id = #{item.id} then #{item.age}
                </foreach>
            </trim>

            <trim prefix="age=case" suffix="end,">
                <foreach collection="list" item="item" index="index">
                    when id = #{item.id} then #{item.age}
                </foreach>
            </trim>

        </trim>
        where id in
        <foreach collection="list" index="index" item="item"
                 separator="," open="(" close=")">
            #{item.id,jdbcType=INTEGER}
        </foreach>
    </update>

打印

DEBUG==>  Preparing: update mp_user set name=case when id = ? then ? when id = ? then ? end, age=case when id = ? then ? when id = ? then ? end, age=case when id = ? then ? when id = ? then ? end where id in ( ? , ? ) 
DEBUG==> Parameters: 1(String), eddie1(String), 2(String), dante1(String), 1(String), 19(Integer), 2(String), 20(Integer), 1(String), 19(Integer), 2(String), 20(Integer), 1(String), 2(String)
DEBUG<==    Updates: 2