這篇文章將為大家詳細(xì)講解有關(guān)JPA如何批量保存saveAll,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
創(chuàng)新互聯(lián)長期為成百上千客戶提供的網(wǎng)站建設(shè)服務(wù),團隊從業(yè)經(jīng)驗10年,關(guān)注不同地域、不同群體,并針對不同對象提供差異化的產(chǎn)品和服務(wù);打造開放共贏平臺,與合作伙伴共同營造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為陜州企業(yè)提供專業(yè)的做網(wǎng)站、成都網(wǎng)站制作,陜州網(wǎng)站改版等技術(shù)服務(wù)。擁有十余年豐富建站經(jīng)驗和眾多成功案例,為您定制開發(fā)。
使用了JPA的saveAll方法批量保存一千多條數(shù)據(jù)的問題,但是發(fā)現(xiàn)日志打印卻是一條一條的insert語句。
查看saveAll的源碼,發(fā)現(xiàn)里面是使用了一個for循環(huán)然后一條條的執(zhí)行save方法....
好吧,手動寫一個批量執(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)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
網(wǎng)站欄目:JPA如何批量保存saveAll
網(wǎng)址分享:http://muchs.cn/article22/ghejcc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供靜態(tài)網(wǎng)站、網(wǎng)站排名、營銷型網(wǎng)站建設(shè)、虛擬主機、企業(yè)建站、網(wǎng)站設(shè)計公司
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)