【JAVA开发日常问题】二、使用SpringBoot实现MYSQL批量插入

一、需求背景

SpringBoot没有提供封装好的批量插入的方法,所以自己网上了找了些资料关于批量插入的,不太理想,想要实现SQL语句的批量插入,而不是每条每条插入。

二、解决方案

1. 配置JPA的批量插入参数,使用JPA提供的方法saveAll保存,打印SQL发现实际还是单条SQL的插入。

spring.jpa.properties.hibernate.jdbc.batch_size=500
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.order_updates =true

2. 使用JdbcTemplate的方法构造SQL语句,实现批量插入。


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Marion
 * @date 2020/8/13
 */
@Service
public class JdbcService {

    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    public <T> void saveMsgItemList(List<T> list) {
        // 这里注意VALUES要用实体的变量,而不是字段的Column值
        String sql = "INSERT INTO t_msg_item(groupid, sender_uid) " +
                "VALUES (:groupId, :senderUid)";
        updateBatchCore(sql, list);
    }

    /**
     * 一定要在jdbc url 加&rewriteBatchedStatements=true才能生效
     * @param sql  自定义sql语句,类似于 "INSERT INTO chen_user(name,age) VALUES (:name,:age)"
     * @param list
     * @param <T>
     */
    public <T> void updateBatchCore(String sql, List<T> list) {
        SqlParameterSource[] beanSources = SqlParameterSourceUtils.createBatch(list.toArray());
        namedParameterJdbcTemplate.batchUpdate(sql, beanSources);
    }

}

3. 将插入的数据切割成100一条一次,推荐不超过1000条数据,循环插入。

    @Autowired
    private JdbcService jdbcService;

    private void multiInsertMsgItem(List<Long> uids, String content, boolean hide) {
        int size = uids.size();
        List<MsgItemEntity> data = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            MsgItemEntity mIE = MsgItemEntity.buildMsgItem(MessageGroupType.SYSTEM.getValue(), content, MessageType.TEXT, uids.get(i), hide);
            data.add(mIE);
            if (i % 100 == 0) {
                jdbcService.saveMsgItemList(data);
                data.clear();
            }
        }
        if (data.size() > 0) {
            jdbcService.saveMsgItemList(data);
        }
    }

4. 运行结果。查询SQL是否是正常的批量插入,可以参考文章。MySQL查看实时执行的SQL语句

三、总结

1. JPA找到实现批量插入的还是挺麻烦的,所以还是使用NamedParameterJdbcTemplate来实现批量插入比较方便。

四、参考文档

1. JPA批量操作及性能比对 saveAll -jdbcTemplate.

2. 【JAVA开发日常问题】一、使用SpringBoot实现MYSQL批量插入

猜你喜欢

转载自blog.csdn.net/luomao2012/article/details/107991297