6000多条数据update如果单纯使用save需要2min多钟(这是不能被接受的
主要参考的是
基于JPA的批量增加数据引发的几种方式
其中的第四种方式——原生sql
/**
* 使用数据库原生的方式执行,不需要配置
* @param list
*/
public void batchWithNativeSql(List<User> list) throws SQLException {
String sql = "Insert into t_user(id,name,age) values(?,?,?)";
DataSource dataSource = jdbcTemplate.getDataSource();
try{
Connection connection = dataSource.getConnection();
connection.setAutoCommit(false);
PreparedStatement ps = connection.prepareStatement(sql);
final int batchSize = 10000;
int count = 0;
for(User user :list){
ps.setString(1,user.getId());
ps.setString(2,user.getName());
ps.setInt(3,user.getAge());
ps.addBatch();
count++;
if(count % batchSize == 0 || count == list.size()) {
ps.executeBatch(); //执行
ps.clearBatch(); //清空缓存
}
}
connection.commit();
}catch (SQLException e){
e.printStackTrace();
}
}
很好理解就是通过 ps.setString(1,user.getId());语句来set值进去,然后加到ps.addBatch();,等大概1000条就把就刚刚1000条数据一次性执行