今天使用了JPA的saveAll方法批量保存一千多条数据的问题,但是发现日志打印却是一条一条的insert语句。
查看saveAll的源码,发现里面是使用了一个for循环然后一条条的执行save方法....
好吧,手动写一个批量执行的方法
@Component
public class DbUtils {
private static EntityManager entityManager;
public static final int BATCH_SIZE = 1000;
public static EntityManager getEntityManager() {
if (entityManager == null) {
entityManager = SpringUtils.getBean(EntityManager.class);
}
return entityManager;
}
public static void setEntityManager(EntityManager entityManager) {
//DbUtils.entityManager = entityManager;
}
public static void batchExecute(String sql, List params, Integer batchSize){
if (batchSize == null) {
batchSize = BATCH_SIZE;
}
if(params.size() == 0){
return;
}
Connection conn = null;
Session session = null;
PreparedStatement stmt = null;
try {
session = (Session) getEntityManager().getDelegate();
SessionFactoryImpl sf = (SessionFactoryImpl)session.getSessionFactory();
conn = sf.getJdbcServices().getBootstrapJdbcConnectionAccess().obtainConnection();
stmt = conn.prepareStatement(sql);
conn.setAutoCommit(false);
int index = 0;
for (Object[] objects : params) {
for(int i=0 ; i
stmt.setObject(i+1, objects[i]);
}
stmt.addBatch();
index++;
if (index % batchSize == 0){
stmt.executeBatch();
stmt.clearBatch();
}
}
if (index % batchSize != 0){
stmt.executeBatch();
stmt.clearBatch();
}
conn.commit();
}catch (Exception e){
throw new RuntimeException(e.getMessage());
}finally {
try {
stmt.close();
conn.close();
}catch (SQLException e){
throw new RuntimeException(e.getMessage());
}
}
}
}