This article introduces how to batch insert data to the database using Hibernate. For more information, see.
In the previous notes, we used jdbc and iBATIS to insert data in batches to the database. Using the corresponding interfaces in The Hibernate framework also enables batch data operations. Hibernate caches the recently inserted data in the memory at session-level, first, set a reasonable JDBC batch size in the configuration file hibernate. jdbc. the batch_size parameter is used to specify the number of SQL statements submitted each time. The reason for configuring the hibernate. jdbc. batch_size parameter is to read the database as little as possible. The larger the value of the hibernate. jdbc. batch_size parameter, the fewer reads the database and the faster the speed. Then, the sessions are flush () and clear () at a certain interval, that is, each time a certain amount of data is inserted, they are promptly removed from the internal cache to release the occupied memory. Session implements asynchronous write-behind, which allows Hibernate to explicitly write a batch of operations. The following is an example of using Hibernate to insert data in batches:
The Code is as follows: |
Copy code |
/** * Hibernate inserts data in batches * @ Param recordList */ Public void saveRecordByList (final List <Record> recordList ){ Gethibernatetemplate(cmd.exe cute (new HibernateCallback (){ @ Override Public Object doInHibernate (Session session) throws HibernateException, SQLException { Session. beginTransaction (); // Maximum number of entries submitted each time Final int batchSize = 200; Int count = 0; For (Record record: recordList ){ Session. save (record ); // Submit every 200 data entries If (++ count % batchSize = 0 ){ Session. getTransaction (). commit (); Session. flush (); Session. clear (); Session. beginTransaction (); } } // Submit the remaining data Session. beginTransaction (); Return null; } }); } |
Set the Hibernate. jdbc. batch_size parameter in the hibernate configuration file:
The Code is as follows: |
Copy code |
<! -- Set the hibernate. jdbc. batch_size parameter --> <Hibernate-configuration> <Session-factory> ......... <Property name = "hibernate. jdbc. batch_size"> 200 </property> ......... <Session-factory> <Hibernate-configuration> </SPAN> |