Batch insertion, update, and deletion of Hibernate data

Source: Internet
Author: User

4.2 Hibernate batch processing Hibernate operates the database in an object-oriented way. When the persistence object is operated in an object-oriented way in the program, it is automatically converted to database operations. For example, if you call the delete () method of the Session to delete a persistent object, Hibernate will delete the corresponding data record. When you execute the set Method of the Persistent object, hibernate will automatically convert to the corresponding update method to modify the corresponding records of the database. The problem is, if you need to update 100 records simultaneously, is it necessary to load 100 records one by one and then call the set Method in sequence-this is not only tedious, but also has poor data access performance. For this batch processing scenario, Hibernate provides a batch processing solution. The following describes how to deal with this batch processing scenario from three aspects: Batch insert, batch update, and batch Delete. 4.2.1 batch insert if you need to insert 100 records into the database, Hibernate may usually adopt the following method: 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 as this program runs, it will always fail at some time and throw an OutOfMemoryException (memory overflow exception ). This is because the Hibernate Session holds a required level-1 cache, and all User instances will be cached in the Session-level cache area. To solve this problem, we have a very simple idea: regularly refresh Session cached data into the database, rather than always caching at the Session level. You can consider designing a accumulators. Each time you save a User instance, the number of accumulators increases by 1. Determines whether to fl Session cache data into the database based on the value of the accumulators. The following code snippet adds 100 million User instances: private void testUser () throws Exception {// open Session session = HibernateUtil. currentSession (); // start Transaction tx = session. beginTransaction (); // 100 cycles, insert 100 records for (int I = 0; I <1000000; I ++) {// create a User instance User u1 = new User (); u1.setName ("xxxxx" + I); u1.setAge (I); u1.setNationality ("china "); // cache the Session of the User instance at the session level. save (u1); // when the accumulators are multiples of 20 The data in ession is flushed into the database and the Session cache is cleared. if (I % 20 = 0) {session. flush (); session. clear (); tx. commit (); tx = session. beginTransaction () ;}// submit the transaction tx. commit (); // close the transaction HibernateUtil. closeSession ();} in the code above, when I % 20 = 0, the cache data at the Session is manually written to the database and the transaction is submitted manually. If you do not submit a transaction, the data will still be cached in the transaction-not in the database, and will also cause memory overflow exceptions. This is the processing of Session-level cache, and the second-level cache of SessionFactory should be disabled through the following configuration. Hibernate. cache. use_second_level_cache false note: In addition to manually clearing the Session-level cache, it is best to disable the SessionFactory-level second-level cache. Otherwise, even if you manually clear the Session-level cache, an exception may occur because there is a cache at the SessionFactory level. 4.2.2 The method described above for batch update is also applicable to batch update data. If you need to return multiple rows of data, you can use scroll () to make full use of the performance advantages of server-side cursors. The following code snippet for batch update: private void testUser () throws Exception {// open Session session = HibernateUtil. currentSession (); // start Transaction tx = session. beginTransaction (); // query all records in the User table. ScrollableResults users = session. createQuery ("from User "). setCacheMode (CacheMode. IGNORE ). scroll (ScrollMode. FORWARD_ONLY); int count = 0; // traverses all records in the User table while (users. next () {User u = (User) users. get (0); u. set Name ("new username" + count); // when count is a multiple of 20, flush the update result from the Session to the database if (++ count % 20 = 0) {session. flush (); session. clear () ;}} tx. commit (); HibernateUtil. closeSession ();} in this way, although batch update can be executed, the effect is very poor. The execution efficiency is not high, and the data query must be executed first, and then the data update must be executed. This update will be a row-by-row update, that is, an update statement must be executed for each row of records updated, low performance. To avoid this situation, Hibernate provides an HQL syntax similar to SQL batch update and batch deletion. 4.2.3 SQL-style batch UPDATE/DELETE HQL statements provided by Hibernate also support the batch UPDATE and DELETE syntax. The syntax format of batch UPDATE and DELETE statements is as follows: UPDATE | delete from? ClassName [WHERE WHERE_CONDITIONS] The above syntax format has the following four points worth noting: ● In the FROM clause, the FROM keyword is optional. That is, the FROM keyword is not allowed. ● Only one class name is allowed in the FROM clause, and the class name cannot have an alias. ● Connections cannot be used in batch HQL statements. explicit or implicit Connections cannot be used. However, subqueries can be used in the WHERE clause. ● The entire WHERE clause is optional. Assume that the name attribute of the User-class instance needs to be modified in batches, and the following code snippet can be used: private void testUser () throws Exception {// open Session session = HibernateUtil. currentSession (); // start Transaction tx = session. beginTransaction (); // defines the HQL statement String hqlUpdate = "update User set name =: newName"; // executes the update int updatedEntities = session. createQuery (hqlUpdate ). setString ("newName", "new name "). executeUpdate (); // submit the transaction tx. commit (); Hibernate Util. closeSession ();} from the code above, we can see that this syntax is very similar to the executeUpdate Syntax of PreparedStatement. In fact, this batch UPDATE of HQL directly draws on the UPDATE Statement of SQL syntax. Note: When using this batch UPDATE syntax, you usually only need to execute an SQL UPDATE statement to complete all updates that meet the conditions. However, you may also need to execute multiple UPDATE statements because of special circumstances such as inheritance ing. For example, if you have a Person instance, it has a Customer subclass instance. When you update the Person instance in batches, you also need to update the Customer instance. If the joined-subclass or union-subclass ing policy is adopted, the Person and Customer instances are stored in different tables, so multiple UPDATE statements may be required. Execute an hql delete statement and use the Query.exe cuteUpdate () method. The following is a code snippet for deleting all the above records: private void testUser () throws Exception {// open the Session instance Session session = HibernateUtil. currentSession (); // start Transaction tx = session. beginTransaction (); // define the HQL statement String hqlUpdate = "delete User" for batch deletion; // execute batch deletion int updatedEntities = session. createQuery (hqlUpdate ). executeUpdate (); // submit the transaction tx. commit (); // disable Session HibernateUtil. clo Sesession();} is an integer value returned by query.exe cuteUpdate (). This value is the number of records affected by this operation. In fact, the underlying operations of Hibernate are completed through JDBC. Therefore, if a batch UPDATE or DELETE operation is converted to multiple UPDATE or DELETE statements, the method returns the number of records affected by the last SQL statement.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.