您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)JPA如何批量保存saveAll,小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
使用了JPA的saveAll方法批量保存一千多條數(shù)據(jù)的問(wèn)題,但是發(fā)現(xiàn)日志打印卻是一條一條的insert語(yǔ)句。
查看saveAll的源碼,發(fā)現(xiàn)里面是使用了一個(gè)for循環(huán)然后一條條的執(zhí)行save方法....
好吧,手動(dòng)寫(xiě)一個(gè)批量執(zhí)行的方法
@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<Object[]> 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<objects.length ; 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()); } } } }
關(guān)于“JPA如何批量保存saveAll”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。