hibernate batch operationsAdvertisements 4.2 Hibernate batch processingHibernate completely object-oriented approach to operating the database, when the program in object-oriented manner operating persistent object will be automatically converted to the database operation. Such as call Session's delete () method to remove the persistent object, Hibernate will be responsible to delete the corresponding data record; when the implementation of persistent object set method, Hibernate will automatically be converted to the corresponding update method, modify the corresponding database record. The problem is if the need to update 100,000 records, is not to load 100,000 records one by one, followed by calling set methods - this is not only cumbersome, data access performance is also very bad. Scenes of this batch, Hibernate provides a batch processing solution, the following were inserted from the batch, batch updates and batch delete three aspects of how the face of this batch of cases. 4.2.1 Bulk InsertIf you need to insert 100 000 records database, Hibernate is usually the practice may use the following: Wrote, Session session = sessionFactory.openSession (); Transaction tx = session.beginTransaction (); for (int i = 0; i <100000; i + +) ( User u = new User (.....); session.save (customer); ) tx.commit (); session.close (); But with this program running, always running at some point fail, and throw OutOfMemoryException (out of memory exception). This is because Hibernate Session holds a Required level cache, all the User instance will be at the Session level cache for the cache of the reason. To solve this problem, there is a very simple idea: Session cache periodically to refresh the data into the database, but not always in the Session-level cache. Consider designing a accumulator, each save a User instance, an increase of 1 accumulator. According to the value of accumulator determine the need to brush Session cache data into the database. The following are examples of additional 100 000 User code fragment: private void testUser()throws Exception { // Open Session Session session = HibernateUtil.currentSession(); // Begin transaction Transaction tx = session.beginTransaction(); // Circular 100 000 times , Insert the 100 000 records for (int i = 0 ; i < 1000000 ; i++ ) { // Create User instances User u1 = new User(); u1.setName("xxxxx" + i); u1.setAge(i); u1.setNationality("china"); // In the Session-level caching User Instance session.save(u1); // Whenever the accumulator is 20 ratios , The data in the Session brush into the database , And empty Session cache if (i % 20 == 0) { session.flush(); session.clear(); tx.commit(); tx = session.beginTransaction(); } } // Commit the transaction tx.commit(); // Turn off the transaction HibernateUtil.closeSession(); } The above code, when i% 20 == 0, the manually Session Department cache data written to the database, and manually commit the transaction. If you do not commit the transaction, the data will remain cached in the Office - did not enter the database, it will cause memory overflow exception. This is Session-level cache handling, the following should also be configured to close the SessionFactory through the level two cache. hibernate.cache.use_second_level_cache false Note: In addition to manually empty the Session-level cache, the best close SessionFactory level 2 cache. Otherwise, even if manually empty the Session-level cache, but also because SessionFactory-level cache, it may raise an exception. 4.2.2 Batch UpdateThe method described above also apply to batch update the data, if the need to return multiple lines of data, you can use the scroll () method, which can take full advantage of server-side cursors performance advantages brought. Here is the code fragment batch updates: Wrote, private void testUser () throws Exception ( / / Open Session Session session = HibernateUtil.currentSession (); / / Start transaction Transaction tx = session.beginTransaction (); / / Check out all the records in the User table ScrollableResults users = session.createQuery ("from User") . SetCacheMode (CacheMode.IGNORE) . Scroll (ScrollMode.FORWARD_ONLY); int count = 0; / / Loop through all the records in the User table while (users.next ()) ( User u = (User) users.get (0); u.setName ("new user name" + count); / / When the count is a multiple of 20, when the results will be updated in the flush to the database from the Session if (+ + count% 20 == 0) ( session.flush (); session.clear (); ) ) tx.commit (); HibernateUtil.closeSession (); ) In this way, although you can perform batch updates, but the effect was very bad. The efficiency is not high, and the need to perform data queries, and then perform data updates, and this update will be updated line by line, that is, each row update, all need to perform an update statement, the performance is very low. To avoid this situation, Hibernate provides a similar SQL batch updates and bulk delete the HQL syntax. 4.2.3 SQL-style bulk update / deleteHibernate HQL statement also provided support for the UPDATE and DELETE syntax batch. Bulk UPDATE and DELETE statement syntax is as follows: UPDATE | DELETE FROM? ClassName [WHERE WHERE_CONDITIONS] On the above syntax has the following four points worth noting: ● in the FROM clause, FROM keyword is optional. That can not write FROM keyword. ● in the FROM clause can only have one class name, class name can not have aliases. ● not used in connection bulk HQL statement, explicit or implicit will not work. But can be used in the WHERE clause in the subquery. ● the WHERE clause is optional. Assumptions need to batch change the User name attribute instance of the class can be completed using the following code fragment: Wrote, private void testUser () throws Exception ( / / Open Session Session session = HibernateUtil.currentSession (); / / Start transaction Transaction tx = session.beginTransaction (); / / Define HQL bulk update statement String hqlUpdate = "update User set name =: newName"; / / Perform the update int updatedEntities = session.createQuery (hqlUpdate) . SetString ("newName", "new name") . ExecuteUpdate (); / / Commit transaction tx.commit (); HibernateUtil.closeSession (); ) As can be seen from the above code, this syntax is very similar to the executeUpdate PreparedStatement syntax. In fact, HQL bulk update this is a direct reference of the SQL syntax of the UPDATE statement. Note: Use this batch update syntax, it is usually only need to perform a SQL's UPDATE statement, you can complete all the updated records to meet the conditions. But may need to perform multiple UPDATE statements, it is because there are special circumstances such as inheritance mapping, for example, a Person instance, it has an instance of a subclass of Customer. When the batch update Person instance, they need to update the Customer instance. If the use of joined-subclass, or union-subclass mapping strategy, Person and Customer instance stored in different tables, so may need multiple UPDATE statements. Implementation of a HQL DELETE, use the same Query.executeUpdate () method, the following is a code to delete all records above, fragments: Wrote, private void testUser () throws Exception ( / / Open the Session instance Session session = HibernateUtil.currentSession (); / / Start transaction Transaction tx = session.beginTransaction (); / / Define HQL batch delete statement String hqlUpdate = "delete User"; / / Implementation of the bulk deletion int updatedEntities = session.createQuery (hqlUpdate) . ExecuteUpdate (); / / Commit transaction tx.commit (); / / Close Session HibernateUtil.closeSession (); ) By the Query.executeUpdate () method returns an integer value is the number of records affected by this operation. In fact, Hibernate is the underlying operation done through JDBC. Therefore, if the UPDATE or DELETE operation volume is converted to UPDATE or DELETE statement number, the method returns the SQL statement is the last number of affected rows. Source: http://blog.sina.com.cn/s/blog_49a91aa90100ixq8.html Tags: data access, lt, implementation, level cache, session level, persistent object, memory, database operation, cache data, database record, batch processing, bulk insert, batch operations, oriented approach, three aspects, batch updates, records database, accumulator
Related Posts of hibernate batch operations
|
|
来自: will_lau > 《hibernate》