MyBatis配置允许批量插入或更新数据

MyBatis配置allowMultiQueries=true允许使用foreach标签批量插入或更新数据

执行update更新操作:

xml 复制代码
<!-- 批量更新 -->
    <update id="updateBatchByKey" parameterType="java.util.List">
        <foreach collection="list" item="item" index="index" separator=";">
            UPDATE order_main_product
            <set>
                <if test="item.factoryId != null">factory_id = #{item.factoryId},</if>
                <if test="item.factoryCode != null and item.factoryCode != ''">factory_code = #{item.factoryCode},</if>
                <if test="item.factoryName != null and item.factoryName != ''">factory_name = #{item.factoryName},</if>
                <if test="item.orderId != null">order_id = #{item.orderId},</if>
                <if test="item.parentId != null">parent_id = #{item.parentId},</if>
                <if test="item.shipmentAmount != null and item.shipmentAmount != ''">shipment_amount =
                    #{item.shipmentAmount},
                </if>
                ......
            </set>
            WHERE id = #{item.id}
        </foreach>
    </update>

执行报错:

sql 复制代码
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE
	order_main_product
SET
	product_count = 1,
	delivery_time = '2024-08' at line 2

错误位置: line: 1

解决:更改jdbc配置,加上allowMultiQueries=true

yml 复制代码
url: jdbc:mysql://172.16.1.145:3306/new_crm?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true

在MySQL连接中设置allowMultiQueries=true允许在SQL语句后使用分号分隔,执行多个命令。

原因:

MyBatis默认情况下不允许批量插入或更新数据的原因是出于安全考虑。在许多情况下,数据的插入和更新都需要经过验证和控制,以确保数据的完整性和一致性。如果允许默认的批量操作,可能会导致不正确的数据插入或更新,从而影响应用程序的正常运行。

通过配置allowMultiQueries=true可以开启MyBatis的批量操作功能。这个配置项告诉MyBatis允许在单个数据库连接中执行多个SQL语句,从而实现批量插入或更新数据的功能。但是要注意,在开启批量操作之前,确保你已经了解并理解了可能引发的安全风险,并且在使用批量操作时要进行适当的验证和控制,以确保数据的完整性和安全性。

尽管 allowMultiQueries 可以用于某些情况下的方便性,但出于安全和性能的考虑,通常不建议在生产环境中启用它。

相关推荐
indexsunny2 分钟前
互联网大厂Java求职面试实战:基于电商场景的技术问答及解析
java·spring boot·redis·kafka·security·microservices·面试指导
Forget_855040 分钟前
RHEL——LVS模式
java·开发语言·lvs
渣瓦攻城狮1 小时前
互联网大厂Java面试:从数据库连接池到分布式缓存及微服务
java·redis·spring cloud·微服务·hikaricp·数据库连接池·分布式缓存
罗超驿1 小时前
13.1 万字长文,深入解析--抽象类和接口
java·开发语言
A懿轩A1 小时前
【Java 基础编程】Java 面向对象进阶:static/final、抽象类、接口、单例模式
java·开发语言·单例模式
lifallen1 小时前
后缀数组 (Suffix Array)
java·数据结构·算法
逆境不可逃2 小时前
LeetCode 热题 100 之 76.最小覆盖子串
java·算法·leetcode·职场和发展·滑动窗口
I_LPL2 小时前
day35 代码随想录算法训练营 动态规划专题3
java·算法·动态规划·hot100·求职面试
百锦再2 小时前
Java中的日期时间API详解:从Date、Calendar到现代时间体系
java·开发语言·spring boot·struts·spring cloud·junit·kafka
A懿轩A2 小时前
【Java 基础编程】Java 枚举与注解从零到一:Enum 用法 + 常用注解 + 自定义注解实战
java·开发语言·python