网上看到一些 解决 批量更新,出现 multi-statement not allow 错误 的解决方案,自己断点查看源码和执行过程,多方总结得出结论
一、首先数据库连接必须增加 allowMultiQueries=true 以支持批量更新,如下
spring.datasource.url=jdbc:mysql://localhost:3306/xxx?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true&allowMultiQueries=true
二、druid.properties 文件配置
主要看 druid.filters=stat,log4j
##下面为连接池的补充设置,应用到上面所有数据源中
#初始化大小,最小,最大
druid.initialSize=5
druid.minIdle=10
druid.maxActive=300
#配置获取连接等待超时的时间
druid.maxWait=60000
#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
druid.timeBetweenEvictionRunsMillis=60000
#配置一个连接在池中最小生存的时间,单位是毫秒
druid.minEvictableIdleTimeMillis=300000
druid.validationQuery=SELECT 1 FROM DUAL
druid.testWhileIdle=true
druid.testOnBorrow=false
druid.testOnReturn=false
#打开PSCache,并且指定每个连接上PSCache的大小
druid.poolPreparedStatements=true
druid.maxPoolPreparedStatementPerConnectionSize=20
#配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
#filters 属性类型是字符串,通过别名的方式配置扩展插件,
#常用的插件有:监控统计用的filter:stat ,日志用的filter:log4j,防御sql注入的filter:wall
#因为wall会导致无法批量更新,所以这里不配置wall,改为在DruidDataSourceConfig 里面配置支持批量更新的wall
#druid.filters=stat,wall,log4j
druid.filters=stat,log4j
#通过connectProperties属性来打开mergeSql功能;慢SQL记录
druid.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
#合并多个DruidDataSource的监控数据
druid.useGlobalDataSourceStat=true
druid.secret = 28ae944fs9f398a90862s6
三、配置 DruidDataSourceSettings.java,主要是把druid.properties 文件 的数据读取过来
package com.xxx.config.database;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.stereotype.Component;
/*
* @ConfigurationProperties 自动读取application.yml 或 application.properties
* @PropertySource 读取指定文件,默认读取application.properties,
* 如果非application.properties,则需要加classpath:
* 如果有中文,需要encoding="UTF-8"
* @PropertySource(value = "classpath:druid.properties",encoding="UTF-8")
*/
@Component
@ConfigurationProperties(prefix = "spring.datasource")
@PropertySource("classpath:druid.properties")
public class DruidDataSourceSettings {
//没有指定${},将使用application.properties 的配置
private String driverClassName;
private String url;
private String username;
private String password;
//${druid.initialSize} 使用 druid.properties 的配置
@Value("${druid.initialSize}")
private int initialSize;
@Value("${druid.minIdle}")
private int minIdle;
@Value("${druid.maxActive}")
private int maxActive;
@Value("${druid.timeBetweenEvictionRunsMillis}")
private long timeBetweenEvictionRunsMillis;