Mybatis批量update多字段信息
使用Mybatis的trim,foreach标签完成数据的批量操作。
Mybatis批量插入
insert into user (id,name) values (1,'aa'),(1.'bb')...
使用mybatis则为如下
<insert id="insertList">
insert into user (id,name) values
<foreach collection="list" item="item" separator=",">
(#{item.id},#{item.name})
</foreach>
</insert>
Mybatis 批量删除
delete from user where id in (1,2,3)
通过open,close标签将id括起来,通过 separator标签将id进行分离
<delete id="deleteList">
delete from user where id in
<foreach collection="list" item="item" open="(" separator="," close=")">
#{item.id}
</foreach>
</delete>
Mybatis 批量更新
一般使用case when 进行数据的批量更新
update user set money =
case when id = 1 and name = 'a' then 200
case when id = 2 and name = 'bb' then 300
where (id,name) in
((1,'a'),(2,'bb'))
此时我们需要做的就是通过trim,foreach 组装出上述的sql
<update id="listUpdate" parameterType="list">
update user
<trim prefix="set">
<trim prefix="money = case" >
<foreach collection="list" item="item" close="end,">
when id =#{item.id} and name = #{item.name} then #{item.inv}
</foreach>
</trim>
</trim>
time = now() where (id,name) in
<foreach collection="list" item="item" open="(" separator="," close=")">
(#{item.id},#{item.name})
</foreach>
</update>
Mybatis 执行时的Sql问题排查
一般使用Mybatis 拼装复杂的sql时比较容易出错,但是由于报错信息有限,有时候并不能清楚的确认问题出在哪里,那么这个时候可以通过debug去确认Mybatis拼装后的具体sql去调整自己的拼接方式。
- 开启debug模式
- 逐步进入至具体的excutor执行的sql
- 如果不确认问题在哪里,可以把编译后的sql复制到mysql客户端执行一遍,它会告诉你的。
以比较容易出错的update为例
关注excutor的doUpdate()方法,在执行此方法中会具体编译需要执行的sql
开启debug之后查看编译后的sql