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>总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Spring Boot 与 Kotlin 上传文件的示例代码
这篇文章主要介绍了Spring Boot 与 Kotlin 上传文件的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2018-01-01
spring boot使用thymeleaf为模板的基本步骤介绍
Spring Boot项目的默认模板引擎是Thymeleaf,这没什么好说的,个人觉得也非常好,下面这篇文章主要给大家介绍了关于spring boot使用thymeleaf为模板的相关资料,需要的朋友可以参考借鉴,下面来一起学习学习吧。2018-01-01
Java读取properties配置文件时,出现中文乱码的解决方法
下面小编就为大家带来一篇Java读取properties配置文件时,出现中文乱码的解决方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧2016-11-11
解决eclipse中maven引用不到已经存在maven中jar包的问题
这篇文章主要介绍了解决eclipse中maven引用不到已经存在maven中jar包的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-10-10


最新评论