java jpa saveall方法优化_JPA批量保存saveAll的问题

今天使用了JPA的saveAll方法批量保存一千多条数据的问题,但是发现日志打印却是一条一条的insert语句。

acfbef491bcca2d8b1978c0f520c2581.png

查看saveAll的源码,发现里面是使用了一个for循环然后一条条的执行save方法....

5cd6708314766b79cb7e760a0fe3949b.png

好吧,手动写一个批量执行的方法

@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());

}

}

}

}


版权声明:本文为weixin_28908857原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。