allowMultiQueries=true
参数的作用:
- 可以在sql语句后携带分号,实现多语句执行。
- 可以执行批处理,同时发出多个SQL语句。
在application-xxx.xml配置文件中,配置数据库的信息
spring:datasource:dynamic:primary: mysqldb # 默认数据源datasource: mysqldb:driverClassName: org.mariadb.jdbc.Driverurl: jdbc:mysql://localhost:3306/data_dev?useUnicode=yes&characterEncoding=UTF-8&useAffectedRows=true&allowMultiQueries=true&autoReconnect=true&failOverReadOnly=false
实例 dao层xml:
- 逐条更新,但一次提交给MySQL服务器而已。
- 利用foreach 遍历循环,传入的list集合数据,批量的进行update
<update id="updateStudentBatch" parameterType="java.util.List"><foreach collection="list" item="item" index="index">UPDATE mutest.student<set><if test="item.name != null">name=#{item.name},</if><if test="item.age != null">age=#{item.age}</if></set>WHEREid=#{item.id};</foreach>
</update>
批处理 rewriteBatchedStatements=true
关于rewriteBatchedStatements这个参数:当前项目中未使用过
- MySQL的JDBC连接的url中要加rewriteBatchedStatements参数,并保证5.1.13以上版本的驱动,才能实现高性能的批量插入。
- MySQL JDBC驱动在默认情况下会无视executeBatch()语句,把我们期望批量执行的一组sql语句拆散,一条一条地发给MySQL数据库,批量插入实际上是单条插入,直接造成较低的性能。
- 只有把rewriteBatchedStatements参数置为true, 驱动才会帮你批量执行SQL
- 另外这个选项对INSERT/UPDATE/DELETE都有效
- 添加rewriteBatchedStatements=true这个参数后的执行速度比较:
- 同个表插入一万条数据时间近似值:
- JDBC BATCH 1.1秒左右 > Mybatis BATCH 2.2秒左右 > 拼接SQL 4.5秒左右
- demo:
- master.jdbc.url=jdbc:mysql://112.126.84.3:3306/outreach_platform?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&rewriteBatchedStatements=true
ps:mysql的话只要在url后面加上&rewriteBatchedStatements=true即可,但是sqlServer则需要以分号分隔;rewriteBatchedStatements=true