Spring JdbcTemplate批量更新速度很慢的问题

来源:互联网 发布:打投做数据是什么 编辑:程序博客网 时间:2024/05/01 16:48

由于一次要执行很多条插入语句(5w),通常通过mysql原生的插入语句会有类似的格式:


insert into TableAAA(f1,f2) values (f11v,f21v),(f12v,f22v)...

执行速度上是没有问题,大概5,6秒。在用JdbcTemplate的时候,就是用batchUpdate方法来写批量执行的语句:

String sql = "insert into code(id,code,status,time) values(?,?,?,?)";jdbcTemplate.batchUpdate(sql, codes, codes.size(), new ParameterizedPreparedStatementSetter<CouponCode>() {    @Override    public void setValues(PreparedStatement preparedStatement, CouponCode code) throws SQLException {        preparedStatement.setInt(1, code.getCid());        preparedStatement.setString(2, code.getCode());        preparedStatement.setInt(3, code.getStatus());        preparedStatement.setDate(4, new Date(new java.util.Date().getTime()));    }});
当执行语句的时候,发现需要十几秒才执行完成,这比原生的sql语句差多了。于是请教他人,最后发现是在数据库连接语句上少了启用rewriteBatchedStatements参数。jdbcTemplate默认在batchUpdate方法中,是一条一条的执行语句。这个在他的驱动代码中可以看到:




所以在连接串上加上

jdbc:mysql://IP:PORT/database?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&rewriteBatchedStatements=true

加上后,重启Tomcat,发现批量执行果然快了。

0 0
原创粉丝点击