mybatis批量更新數據

sql寫法:

UPDATE user_table
        SET user_name= CASE id
            WHEN 1 THEN '張三'
            WHEN 2 THEN '李四'
            WHEN 3 THEN '王二'
        END
    WHERE id IN (1,2,3)

更新多個字段:

UPDATE user_table
        SET user_name= CASE id
            WHEN 1 THEN '張三'
            WHEN 2 THEN '李四'
            WHEN 3 THEN '王二'
        END,
        SET user_card= CASE id
            WHEN 1 THEN '001'
            WHEN 2 THEN '002'
            WHEN 3 THEN '003'
        END
    WHERE id IN (1,2,3)

WHERE id IN (1,2,3)不寫也可以執行,在這裏可以提升sql性能,避免全表掃描

mybatis寫法:

mapper.java:

void updateUser(@Param("list") List<User> userList);

xml:

       <update id="updateUser" parameterType="java.util.List">
        update user_table
        <trim prefix="set" suffixOverrides=",">
            <trim prefix="user_name=case" suffix="end,">
                <foreach collection="list" item="item" index="index">
                     when id=#{item.id} then #{item.userName}
                </foreach>
            </trim>
        </trim>
        where id in
        <foreach collection="list" item="item" open="(" separator="," close=")">
            #{item.id}
        </foreach>
    </update>

更新多個字段

    <update id="updateUser" parameterType="java.util.List">
        update user_table
        <trim prefix="set" suffixOverrides=",">
            <trim prefix="user_name=case" suffix="end,">
                <foreach collection="list" item="item" index="index">
                     when id=#{item.id} then #{item.userName}
                </foreach>
            </trim>
            <trim prefix="user_card=case" suffix="end,">
                <foreach collection="list" item="item" index="index">
                    when id=#{item.id} then #{item.userCard}
                </foreach>
            </trim>
        </trim>
        where id in
        <foreach collection="list" item="item" open="(" separator="," close=")">
            #{item.id}
        </foreach>
    </update>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章