mybatis 实现批量更新多个字段

  • Post author:
  • Post category:其他

一条记录update一次,性能比较差,容易造成阻塞。

MySQL没有提供直接的方法来实现批量更新,但可以使用case when语法来实现这个功能。

1

2

3

4

5

6

7

8

9

10

11

12

UPDATE course

    SET name = CASE id 

        WHEN 1 THEN ‘name1’

        WHEN 2 THEN ‘name2’

        WHEN 3 THEN ‘name3’

    END, 

    title = CASE id 

        WHEN 1 THEN ‘New Title 1’

        WHEN 2 THEN ‘New Title 2’

        WHEN 3 THEN ‘New Title 3’

    END

WHERE id IN (1,2,3)

 

 

这条sql的意思是,如果id为1,则name的值为name1,title的值为New Title1;依此类推。

在Mybatis中的配置则如下:

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

<update id=”updateBatch” parameterType=”list”>

            update course

            <trim prefix=”set” suffixOverrides=”,”>

             <trim prefix=”peopleId =case” suffix=”end,”>

                 <foreach collection=”list” item=”i” index=”index”>

                         <if test=”i.peopleId!=null”>

                          when id=#{i.id} then #{i.peopleId}

                         </if>

                 </foreach>

              </trim>

         

       <trim prefix=”unitsid =case” suffix=”end” >

                  <foreach collection=”list” item=”i” index=”index”>

                          <if test=”i.unitsid!=null”>

                           when id=#{i.id} then #{i.unitsid}

                          </if>

                  </foreach>

           </trim>

             </trim>

            where

            <foreach collection=”list” separator=”or” item=”i” index=”index” >

              id=#{i.id}

          </foreach>

</update>