1、需求背景html
SpringBoot没有提供封装好的批量插入的方法,因此本身网上了找了些资料关于批量插入的,不太理想,想要实现SQL语句的批量插入,而不是每条每条插入。java
2、解决方案spring
1. 配置JPA的批量插入参数,使用JPA提供的方法saveAll保存,打印SQL发现实际仍是单条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语句,实现批量插入。ide
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语句ui
3、总结url
1. JPA找到实现批量插入的仍是挺麻烦的,因此仍是使用NamedParameterJdbcTemplate来实现批量插入比较方便。.net
4、参考文档hibernate