Mysql + Mybatis 批量更新语句
前言
新入职的公司在Mybatis框架上,用的是@XXXProvider注解+SQL语句构建器的形式去实现动态SQL。恰巧Mybatis官网里也没有提到这一点,所以写一下这篇文章。
依赖:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
下面介绍3种方式:
1. Batch Update
- url后设置allowMultiQueries=true



总结:关键在于数组元素通过"[ ]"定位,update语句之间通过" ; "隔断,以及开启配置allowMultiQueries=true。相似的Map中的元素可以通过"#{MapObject.KeyName}"的形式匹配
2. CASE WHEN
这里只写一下最终的SQL,具体拼写方式就由各位各自发挥吧
update teacher
set name = (
case
when id = #{teacherList[0].id} then #{teacherList[0].name}
when id = #{teacherList[1].id} then #{teacherList[1].name}
end
),telephone = (
case
when id = #{teacherList[0].id} then #{teacherList[0].telephone}
when id = #{teacherList[1].id} then #{teacherList[1].telephone}
end
)
where id in (#{teacherList[0].id},#{teacherList[1].id})
3. JOIN
UPDATE teacher a JOIN
(
SELECT #{teacherList[0].id} AS id, #{teacherList[0].name} AS name, #{teacherList[0].telephone} AS telephone
UNION ALL
SELECT #{teacherList[1].id} AS id, #{teacherList[1].name} AS name, #{teacherList[1].telephone} AS telephone
) b USING(id)
SET a.name=b.name,a.telephone=b.telephone
性能与选择:
具体性能测试结果可以参考大佬的文章:https://www.cnblogs.com/AaronCui/p/10968893.html
后续有时间再去用Explain语句看一下具体的执行过程,看看执行差异在哪里。
参考文章:
https://www.cnblogs.com/AaronCui/p/10968893.html
https://blog.csdn.net/daodfs111/article/details/105630711

浙公网安备 33010602011771号