Mybatis批量更新报错

时间:2025-01-24 16:14:05

Mybatis批量更新报错

  • 1. 问题描述
  • 2. 问题分析
  • 3. 解决方案

1. 问题描述

使用批量更新,一直报语法错误,多次检查Mapper文件发现语法没啥问题,就是每次执行都是语法错误,花了好一会时间,特此记录一下。
错误信息如下:

nested exception is : 
### Error updating database.  Cause: .: 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 db_marketing.activity SET activity_status = 4, ' at line 13
### The error may involve -Inline
### The error occurred while setting parameters

Mapper文件如下

    <!-- 通过主键批量更新 -->
    <update id="updateBatch" parameterType="list">
        <foreach collection="list" index="index" item="item" separator=";">
            update db_marketing.activity
            <set>
                <if test=" != null">
                    activity_status = #{},
                </if>
                <if test=" != null and  != ''">
                    update_uid = #{},
                </if>
                <if test=" != null and  != ''">
                    update_name = #{},
                </if>
                <if test=" != null">
                    update_time = #{},
                </if>
            </set>
            WHERE id = #{}
        </foreach>
    </update>

2. 问题分析

通过debug发现程序没什么问题,本身sql语法又没什么问题,那肯定是配置问题了。
通过搜素搜发现需要配置参数allowMultiQueries=true。
原配置无此参数。

jdbc:mysql://10.39.201.254:3306/db_marketing?autoReconnect=true&useUnicode=true&characterEncoding=utf-8

3. 解决方案

错误就是源于mybatis默认是不支持批量更新的。
如果想要进行批量更新,需要在连接数据库的地址上加一个配置,内容如下:

  1. 如果配置文件是
jdbc:mysql://10.39.201.254:3306/db_marketing?allowMultiQueries=true&autoReconnect=true&useUnicode=true&characterEncoding=utf-8
  1. 如果配置文件是
spring:
  datasource:
    type: 
    #MySQL配置
    driver-class-name: 
    url: jdbc:mysql://localhost:3306/mall?allowMultiQueries=true&useUnicode=yes&characterEncoding=UTF-8&useInformationSchema=true&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
    username: root
    password: 123456
这里还有个小插曲,就是我们项目使用的是Apollo配置的,在本地配置或者是不生效的。
通过Apollo默认配置地址:
C:\opt\settings 
设置读取本地缓存:env=LOCAL
C:\opt\data找到对应项目的cache缓存配置,修改URL即可

=jdbc\:mysql\://10.39.201.254\:3306/db_marketing?allowMultiQueries\=true&autoReconnect\=true&useUnicode\=true&characterEncoding\=utf-8