BULK INSERT
Hibernate enforces a first-level cache with limited cache space, and if there are too many SQL statements for a bulk operation, it will fail (memory overflow).
Therefore, in bulk operations, each execution of a batch of SQL statements, you need to flush the cache, such as the following, each execution of 20 SQL, refresh the cache.
1 for ( int i = 0; I < 10000; I++) { 2 User u = new User (" Zhang San ", 20," Guangzhou, China " 3 Sess.save (u); 4 if (i% = = 0 5 Sess.flush (); 6 Sess.clear (); 7 } 8}
In addition to scavenging session-level caches, Hibernate also recommends the following configuration to turn off the sessionfactory level two cache
Hibernate.cache.use_second_level_cache false
Batch Update
As with bulk inserts, you need to empty the first-level cache.
Before updating the data, you need to isolate the data and use the scroll () method to isolate the data, using the performance benefits of the cursor (next () method).
such as the following,
1Scrollableresults users = Sess.createquery ("From User")2 . Setcachemode (Cachemode.ignore)3 . Scroll (scrollmode.forward_only);4 intCount = 0;5 while(Users.next ()) {6User U = (user) users.get (0);7U.setname ("New user name" +count);8 if(++count% 20 = = 0) {9 Sess.flush ();Ten sess.clear (); One } A}
The above is a progressive update, which is appropriate for each row to be updated to a different value. This update is slow, and the following update is a true bulk update, with both the query and the update using the same statement, for all rows to be updated to the same value.
DML-style batch update
1 String hqlupdate = "Update User u set name =: NewName"; 2 int updateentities = sess.createquery (hqlupdate)3 . setString ("NewName", "New name" )4 . executeupdate ();
DML-style Bulk Delete
1 String hqlupdate = "Delete User"; 2 // returns the number of rows affected by the last SQL statement 3 int updateentities = sess.createquery (hqlupdate)4 . executeupdate ();
DML-style performance is significantly better than the previous one, but it seems that all rows can be updated to the same value at the time of the update, and only the number of rows affected by the last SQL can be returned at the time of deletion.
Hibernate's bulk operations