mybatis批量更新出现SQL报错

x33g5p2x  于2022-02-18 转载在 其他  
字(1.6k)|赞(0)|评价(0)|浏览(212)

mybatis批量更新出现SQL报错

一、问题重现

1.配置文件

spring:
  #DataSource数据源
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/mybatis_test?useSSL=false&amp
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver

#MyBatis配置
mybatis:
  type-aliases-package: com.hl.mybatis.pojo #别名定义
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #指定 MyBatis 所用日志的具体实现,未指定时将自动查找
    map-underscore-to-camel-case: true #开启自动驼峰命名规则(camel case)映射
    lazy-loading-enabled: true #开启延时加载开关
    aggressive-lazy-loading: false #将积极加载改为消极加载(即按需加载),默认值就是false
    lazy-load-trigger-methods: "" #阻挡不相干的操作触发,实现懒加载
    cache-enabled: true #打开全局缓存开关(二级环境),默认值就是true

2.sql

@Update({"<script>" +
            "<foreach item='item' collection='list' index='index' open='' close='' separator=';'>" +
            " UPDATE tb_user " +
            "<set>" +
            "<if test='item.userAccount != null'>user_account = #{item.userAccount},</if>" +
            "<if test='item.userPassword != null'>user_password=#{item.userPassword}</if>" +
            "</set>" +
            " WHERE user_id = #{item.userId} " +
            "</foreach>" +
            "</script>"})
    int updateBatch(@Param("list")List<UserInfo> userInfoList);

3.测试

查看控制台错误

发现这里告诉我有一个语法错误,然后发现user_id,有一个符号。>

这里经过测试更新一条是成功的

二、问题分析

Mybatis映射文件中的sql语句默认是不支持以" ; " 结尾的,也就是不支持多条sql语句的执行

但是在SQL编辑器中执行多条sql语句的时候是可以以分号结尾的,如:

三、解决方法

在application.properties配置文中的数据源url后面添加一个参数

&allowMultiQueries=true【允许sql语句中有多个insert或者update语句 == 支持sql批量操作】

原来的配置文件:

url: jdbc:mysql://127.0.0.1:3306/mybatis_test?useSSL=false&amp

现在的配置文件

url: jdbc:mysql://127.0.0.1:3306/mybatis_test?useSSL=false&amp&&allowMultiQueries=true

再次测试

相关文章