Methods and Techniques for batch database insertion using different ORM frameworks in java
1. Use executeBatch in jdbc Mode
In JDBC, you can use the executeBatch () method to reduce the number of database calls, such:
Statement pstmt = conn. createStatement (); pstmt. addBatch (insert into settings values (3, 'xiaomi ', 'female'); pstmt. addBatch (insert into settings values (4, 'lily', 'female); pstmt. addBatch (insert into settings values (5, 'John, Male'); pstmt. addBatch (insert into settings values(6, 'xiaoming ', 'male' too many pstmt.exe cuteBatch ();
2. Use hibernate framework session. save () to save data
To implement batch insert in hibernate, you must control the size of the first-level cache by calling flush () and calling clear () later.
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) {// write 50 pieces of data into the database at a time and release the memory session. flush (); session. clear () ;}} tx. commit (); session. close ();
3. Batch add data using the MyBatis framework
In the insert tag of the corresponding xml in the mapping File of MyBatis, insert values cyclically. The following code is used:
insert into STUDENT( ID,NAME,SEX) values
( #{item.id},#{item.name},#{item.sex})