SpringBoot+Mybatis+Druid批量更新 multi-statement not allow异常
注:该文是本博主记录学习之用,没有太多详细的讲解,敬请谅解!
在日常的开发过程中难免会有批量操作的功能,Mybatis集成Druid批量更新时经常会出现Error updating database. Cause: java.sql.SQLException: sql injection violation, multi-statement not allow 异常。导致该异常出现是因为Druid的multiStatementAllow默认是false,所以需要开启,设置成true。
一、解决方法
- 配置数据库连接,添加allowMultiQueries=true
- 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall’用于防火墙,此处去除防火墙
spring.datasource.druid.filters=config,stat,slf4j
配置过滤器wall的参数
spring.datasource.druid.filter.wall.config.multi-statement-allow=true
注:wall是com.alibaba.druid.wall.WallFilter的简称,提供sql的检查和过滤等功能,默认这里会对混合SQL进行拦截,此处为了执行大SQL,可关闭防火墙功能。
如果需要开启wall监控,同时允许multiStatementAllow,就不要在application.yml中配置filter,自己定义。
@Bean
@ConfigurationProperties(prefix = “spring.datasource”)
public DataSource dataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
List filterList=new ArrayList<>();
filterList.add(wallFilter());
druidDataSource.setProxyFilters(filterList);
return druidDataSource;
}
@Bean
public WallFilter wallFilter(){
WallFilter wallFilter=new WallFilter();
wallFilter.setConfig(wallConfig());
return wallFilter;
}
@Bean
public WallConfig wallConfig(){
WallConfig config =new WallConfig();
config.setMultiStatementAllow(true);//允许一次执行多条语句
config.setNoneBaseStatementAllow(true);//允许非基本语句的其他语句
return config;
}
注:本文讲解的是基于Springboot,如果是Spring项目请参考官网配置https://github.com/alibaba/druid/wiki/%E9%85%8D%E7%BD%AE-wallfilter
________________________________________________________________________________________
logback配置Druid Filter
现在大多数Druid配置都是log4j作为logger,但是logback作为新一代的日志框架,我们有理由使用logback配置Druid Filter,之前的配置是:
dataSourceA.filters=stat,wall,log4j
Druid支持配置多种Filter,配置信息保存在druid-xxx.jar!/META-INF/druid-filter.properties下面,具体如下:
druid.filters.default=com.alibaba.druid.filter.stat.StatFilter
druid.filters.stat=com.alibaba.druid.filter.stat.StatFilter
druid.filters.mergeStat=com.alibaba.druid.filter.stat.MergeStatFilter
druid.filters.counter=com.alibaba.druid.filter.stat.StatFilter
druid.filters.encoding=com.alibaba.druid.filter.encoding.EncodingConvertFilter
druid.filters.log4j=com.alibaba.druid.filter.logging.Log4jFilter
druid.filters.slf4j=com.alibaba.druid.filter.logging.Slf4jLogFilter
druid.filters.commonlogging=com.alibaba.druid.filter.logging.CommonsLogFilter
druid.filters.commonLogging=com.alibaba.druid.filter.logging.CommonsLogFilter
druid.filters.wall=com.alibaba.druid.wall.WallFilter
druid.filters.config=com.alibaba.druid.filter.config.ConfigFilter
众所周知,logback是slf4j的实现类,按照规定格式,改成下面就可以了:
dataSourceA.filters=stat,wall,slf4j