最近在做项目的时候,需要批量插入数据。然后使用saveAll()在本地跑速度还好,打包在服务器上跑的时候发现执行saveAll()时sql在控制台一条一条打印,速度超级慢。后面使用JdbcTemplate,解决了这个问题,在次记录。
@Autowired
private JdbcTemplate jdbcTemplate;
使用autowired注入jdbcTemplate。
@Override
public void batchInsertUsers(List<Student> list) {
String sql = "insert into tbl_student(name, age, class) values(?, ?, ?)";
jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
public void setValues(PreparedStatement ps, int i) throws SQLException {
String name= list.get(i).getName();
int age = list.get(i).getAge();
String class= list.get(i).getClass();
ps.setString(1, name);
ps.setInteger(2, age);
ps.setString(3, class);
}
public int getBatchSize() {
return list.size();
}
});
}
只需要把sql和实体改成自己的就行了。
最重要的一点,在application.properties的连接数据库Url加上rewriteBatchedStatements=true。只有把rewriteBatchedStatements参数置为true, 驱动才会帮你批量执行SQL
spring.datasource.url=jdbc:mysql://localhost:3306/audit_declaration?characterEncoding=utf8&useSSL=true&serverTimezone=UTC&verifyServerCertificate=false&rewriteBatchedStatements=true