java中不同的ORM架構實現對資料庫批量插入資料庫的方式與技巧

來源:互聯網
上載者:User

java中不同的ORM架構實現對資料庫批量插入資料庫的方式與技巧
1.jdbc方式中使用executeBatch實現

JDBC中在做資料插入、更新、刪除操作,可以使用executeBatch()方法減少資料庫調用次數,如:

 

Statement pstmt = conn.createStatement();pstmt.addBatch(insert into settings values(3,'小米','女'));pstmt.addBatch(insert into settings values(4,'小李','女'));pstmt.addBatch(insert into settings values(5,'小王','男'));pstmt.addBatch(insert into settings values(6,'小明','男'));pstmt.executeBatch();

2.採用hibernate架構session.save()儲存資料
在hibernate中實現批量插入,必須通過經常的調用 flush() 以及稍後調用 clear() 來控制第一級緩衝的大小。

 

 

Session session = sessionFactory.openSession();Transaction tx = session.beginTransaction();   for ( int i=0; i<100000; i++ ) {Student entity = new Student(.....);session.save(entity);if ( i % 50 == 0 ) { //每次批量把50條資料寫入資料庫並釋放記憶體session.flush();session.clear();}}   tx.commit();session.close();

3.採用MyBatis架構批量新增資料
在MyBatis的mapping檔案中的相應xml的insert標籤中,對插入的值採用迴圈的方式。如下面代碼:

 

 

     insert into STUDENT( ID,NAME,SEX)    values             ( #{item.id},#{item.name},#{item.sex})      


 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.