最近在业务中涉及使用批量更新的方式将mysql数据库中的数据进行更新:
<update id="updateDebitInfo" parameterType="java.util.List">
<foreach collection="list" item="i" index="index" separator=";">
update PayLimit
set
SingleLimit = #{i.singleLimit},
Daylimit = #{i.dayLimit}
where Id = #{i.Id}
</foreach>
</update>
看似很平静的一个sql语句,但是一直在提示:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'select 'world'' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
表面上看,可能会考虑MySQL版本的问题,但是实际上重点在于前半段:语法错误;但是把该sql语句填充好参数在数据库中执行直接成功,这又是为什么呢?
后来在网上找到一个资料,提到了mybatis对多个以 ; 进行拼接的多个update sql语句就会有这个问题,因为在mybatis中对mysql数据库进行更新时,mybatis无法识别 ; 所以就会提示 语法错误。
解决这个问题,需要我们在配置文件中添加:
String url = "jdbc:mysql://localhost:3306?allowMultiQueries=true";
对于这个属性的配置,官方文档中的解释:
allowMultiQueries
Allow the use of ';' to delimit multiple queries during one statement (true/false), defaults to 'false', and does not affect the addBatch() and executeBatch() methods, which instead rely on rewriteBatchStatements.
Default: false
Since version: 3.1.1
这样我们就可以在mybatis中很好的屏蔽掉不支持 ; 的情况,直白的说就是,开启了这个属性就是开启了MySQL批量语句的开关。
至于为什么在没有配置该属性之前我的批量insert不提示任何问题呢?而这个属性到底为什么可以实现这个作用呢?下篇博文将一一介绍!