Mybatis之批量更新操做

Mybatis之批量更新操做

 

更新單條記錄

1html

UPDATE course SET name 'course1' WHERE id = 'id1';java

 

更新多條記錄的同一個字段爲同一個值

1sql

UPDATE course SET name 'course1' WHERE id in ('id1''id2', 'id3);ide

 

更新多條記錄爲多個字段爲不一樣的值

比較普通的寫法,是經過循環,依次執行update語句。性能

Mybatis寫法以下:spa

1code

2htm

3blog

4ci

5

6

7

8

9

<update id="updateBatch"  parameterType="java.util.List">  

    <foreach collection="list" item="item" index="index" open="" close="" separator=";">

        update course

        <set>

            name=${item.name}

        </set>

        where id = ${item.id}

    </foreach>      

</update>

 

一條記錄update一次,性能比較差,容易形成阻塞。

MySQL沒有提供直接的方法來實現批量更新,但可使用case when語法來實現這個功能。

1

2

3

4

5

6

7

8

9

10

11

12

UPDATE course

    SET name CASE id 

        WHEN THEN 'name1'

        WHEN THEN 'name2'

        WHEN THEN 'name3'

    END

    title = CASE id 

        WHEN THEN 'New Title 1'

        WHEN THEN 'New Title 2'

        WHEN 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=" roadgridid =case" suffix="end,">

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

                         <if test="i.roadgridid!=null">

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

                         </if>

                 </foreach>

              </trim>

              

              <trim prefix="type =case" suffix="end," >

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

                         <if test="i.type!=null">

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

                         </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>

相關文章
相關標籤/搜索