mybatis 批量插入和批量更新

一.批量插入

批量插入时,可以借助标签构造多个数据执行插入

  1. 传入参数为List
  2. 执行sql语句如下
<insert id="saveBatch" parameterType="java.util.List">
    insert into customer
     (name, password, age, weight) 
     values
     <foreach collection="list" separator="," item="item">
         (#{item.name}, #{item.password}, #{item.age}, #{item.weight})
     </foreach>
 </insert>
二. 批量更新

批量更新时,需要借助 标签

1. 方式一: 执行多条更新sql

  • 修改连接配置加上allowMultiQueries=true
jdbc.jdbcUrl=jdbc:mysql://127.0.0.1:3306/database?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
  • 多条sql如下
<update id="updateCustomer">
       <foreach close=";" collection="list" item="item" open=" " separator=";">
           update customer
           set
           		name= #{item.name},
           		password = #{item.password},
           		age = #{item.age}
           where id =  #{item.id}
       </foreach>
</update>
  • 这种方式本质上是一次性执行多条更新sql语句

2. 方式二:借助case when

  • 传入对象List
  • 原生更新执行sql语句如下
update customer
set 
	name= case id 
	    WHEN 1 THEN 'zhangsan'
	    WHEN 2 THEN 'lisi'
	    WHEN 3 THEN 'wangwu'
	end, 
	age = case id  
	    WHEN 1 THEN 123
	    WHEN 2 THEN 456
	    WHEN 3 THEN 789
	end
where id IN (1,2,3)

这段sql的含义是,根据id更新 name age 字段, 分别当id等于1 or 2 or 3 时,更新其值

  • 使用mybatis标签做法如下
   update customer
   set
       name = case id
       <foreach collection="list" item="item" index="index">
           when #{item.id} then #{item.name}
       </foreach>
   	   end,
   	   age = case id
       <foreach collection="list" item="item" index="index">
           when #{item.id} then #{item.age}
       </foreach>
   	   end
   where id in
   <foreach collection="list" item="item" open="(" close=")" separator=",">
       #{item.id}
   </foreach>
  • 如果传入的list非必填,则需要进行判空处理
where 1 = 1
<if test="list!= null and list.size() > 0">
    and id in
    <foreach collection="list" item="item" open="(" separator="," close=")">
        #{item.id}
    </foreach>
</if>

你可能感兴趣的:(mybatis)