Mybatis批量插入和批量更新失败问题
作者:一棵星
这篇文章主要介绍了Mybatis批量插入和批量更新失败问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
背景
Mybatis在执行批量插入(方式二)和批量更新操作时,如果连接参数allowMultiQueries=false(默认),会批量操作失败,而且sql语句copy出来运行正常
报错如下图:

如何解决此类问题
在设置数据库连接时,添加allowMultiQueries=true
spring:
datasource:
url: jdbc:mysql://localhost:3306/db-test?allowMultiQueries=trueallowMultiQueries 参数
allowMultiQueries 是 MySQL 数据库连接参数之一,用于指示是否允许在单个查询中执行多个 SQL 语句。
如果设置为 true,则允许执行多个 SQL 语句,以分号 ; 分隔。
这在某些情况下可能会导致安全风险,因为它可能会受到 SQL 注入攻击的影响。
因此,默认情况下,allowMultiQueries 通常被设置为 false,以提高安全性。
Mybatis批量插入
方式一,单条SQL插入,allowMultiQueries=false,不会报错
void batchInsert(@Param("list") List<UserInfo> list);<insert id="batchInsert">
insert into t_user_info
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="list[0].username != null">
username,
</if>
<if test="list[0].pwd != null">
pwd,
</if>
<if test="list[0].createTime != null">
create_time,
</if>
</trim>
values
<foreach collection="list" item="item" index="index" separator=",">
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="item.username != null">
#{item.username},
</if>
<if test="item.pwd != null">
#{item.pwd},
</if>
<if test="item.createTime != null">
#{item.createTime},
</if>
</trim>
</foreach>
</insert>方式二,多条SQL插入,allowMultiQueries=false,会报错
void batchInsert(@Param("list") List<UserInfo> list);<insert id="batchInsert">
<foreach collection="list" item="item" index="index" separator=";">
insert into t_user_info
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="item.username != null">
username,
</if>
<if test="item.pwd != null">
pwd,
</if>
<if test="item.createTime != null">
create_time,
</if>
</trim>
values
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="item.username != null">
#{item.username},
</if>
<if test="item.pwd != null">
#{item.pwd},
</if>
<if test="item.createTime != null">
#{item.createTime},
</if>
</trim>
</foreach>
</insert>Mybatis批量更新,allowMultiQueries=false,会报错
void batchUpdate(@Param("list") List<UserInfo> list);<update id="batchUpdate">
<foreach collection="list" item="item" index="index" open="" close="" separator=";">
update t_user_info
<set>
<if test="item.username != null">
username = #{item.username},
</if>
<if test="item.pwd != null">
pwd = #{item.pwd},
</if>
<if test="item.updateTime != null">
update_time = #{item.updateTime},
</if>
</set>
where id = #{item.id}
</foreach>
</update>总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
