使用Spring JdbcTemplate进行批量插入数据

357 阅读1分钟

合理使用索引,避免索引失效。批量插入时可以暂时关闭索引,插入结束后再重建索引。

考虑批量插入的数据规模,如果非常大,可以采取分批执行,每次一定数据量,避免内存溢出。

检查日志,分析批量插入的耗时情况,进行参数调优。

考虑使用其他批量插入工具,如 mybatis 提供的 batch 方式。

@SpringBootApplication
@Slf4j
public class BatchInsertApplication implements CommandLineRunner {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public static void main(String[] args) {
        SpringApplication.run(BatchInsertApplication.class, args);
    }

    @PostConstruct
    public void init() {
        jdbcTemplate.execute("drop table IF EXISTS `testuser`;");
        jdbcTemplate.execute("create TABLE `testuser` (\n" +
                "  `id` bigint(20) NOT NULL AUTO_INCREMENT,\n" +
                "  `name` varchar(255) NOT NULL,\n" +
                "  PRIMARY KEY (`id`)\n" +
                ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
    }

    @Override
    public void run(String... args) {

        long begin = System.currentTimeMillis();
        String sql = "INSERT INTO `testuser` (`name`) VALUES (?)";
        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
                preparedStatement.setString(1, "usera" + i);
            }

            @Override
            public int getBatchSize() {
                return 10000;
            }
        });
        log.info("took : {} ms", System.currentTimeMillis() - begin);
    }
}

学习:Java 业务开发常见错误 100 例学习笔记