Batch processing of data in Hibernate

Source: Internet
Author: User
Tags bulk insert

First, batch processing operations

Batch processing of data refers to the processing of large amounts of data in a transactional scenario. In applications where bulk operations are difficult to avoid, Hibernate provides the following ways to process data in batches:

(1) using HQL for bulk operations database level

(2) using the JDBC API for bulk operations database level

(3) Using session for batch operations will be cached

1. Using HQL for bulk operations

HQL can query data or BULK INSERT, update, and delete data. HQL bulk operations are actually done directly in the database, and the processed data does not need to be loaded into the session cache. Use the Executeupdate () method of the query interface to execute the HQL statement for inserting, updating, and deleting.

Take EMP and Dept as an example:

Example: adding 3 departments in bulk

        @Test    publicvoid  addtest () {        String hql= ' INSERT INTO Dept (deptname ) Select D.deptname| | D.deptno from Dept D where d.deptno>0 ";        Query Query=session.createquery (hql);         int count=query.executeupdate ();        System.out.println ("Add ok!!" );    }

Output Result:

2. Batch operations using the JDBC API

When using the JDBC API to bulk execute INSERT, modify, and DELETE statements in hibernate applications, you need to use the DoWork (work) method of the session to perform the actions specified by the work object, called the Execute () method of the Working object. The session passes the currently used database connection to the Execute () method and performs the persistence operation.

Example: Implementing bulk modification of department names

Change the department number greater than 3 to the development department

Note: The connection used by this mode is still the original connection object, and the command object is still created from the connection, note that this is the SQL statement, not the HQL statement

@Test Public voidupdatetest () {FinalString sql= "Update Dept set deptname=? where Deptno>? "; work=NewWork () { Public voidExecute (Connection con)throwssqlexception{PreparedStatement PS=con.preparestatement (SQL); Ps.setstring (1, "Development Department"); Ps.setint (2, 3); intCount=ps.executeupdate (); //System.out.println (count);            }        };        Session.dowork (work); System.out.println ("Update OK!!!"); Copy the Code

Implementation results:

3. Implement the session for batch operation

Using the session object to handle a large number of persisted objects requires the timely emptying of objects from the cache that have been processed and are no longer accessible. You can call the flush () method to force the synchronization of the cache and the database after processing an object or a small batch of objects, and then call the clear () method to empty the cache.

Example: Adding 15 employees in bulk

  /** Session Implementation Batch Add 15 employees*/@Test Public voidaddsessiontest () { for(inti=0;i<=15;i++) {EMP emp=NewEmp (); Emp.setempname ("Hehe" +i); Dept Dept=NewDept (); Dept.setdeptno (1);                        Emp.setdept (dept);                        Session.save (EMP); if(i%10==0) {Session.flush ();            Session.clear (); }} System.out.println ("Add ok!!"); Copy the Code

Output Result:

Second, HQL connection query

The HQL provides a connection as shown in the following table:

Internal connection:

Grammar:

From Entity INNER JOIN Entity.property

Example: Using an internal connection to query an employee's subordinate department

Each element in the list collection is an object array, followed by the Department's first memory address

    /*       * Internal Connection  employee      Subordinate Department */         @Test    publicvoid  Innertest () {                query Query=session.createquery ("from Dept D inner join D.emps");          List<Object[]> list = query.list ();            for (object[] item:list) {              // an item is an array             System.out.println ((Dept) item[ 0]). Getdeptname () + "\ T" + ((EMP) item[1]). Getempname ());}              }

Output Result:

Implicit Intra-connection:

In the HQL query statement, if the EMP class is assigned an alias of "E", the Deptname property of the Dept object can be accessed through the E.dept.deptname form. Use implicit in-connection to query employee information by department.

Example: Querying employee information by departmental criteria

  /*      * Implicit intra-connection query     employee information by departmental conditions */                @Test        publicvoid  Hidetest () {                        query Query=session.createquery ("from Emp e where e.dept.deptname= ' development Department '");              List<Emp> list = query.list ();                for (Emp item:list) {                  // an item is an array                  System.out.println ( Item.getempname ());              }        }        

Output Result:

3. Urgent internal Connection

Example: query all employee names and subordinate department names to use keyword Fetch

  /*          * Urgent Internal connection  query all employee names and          subordinate department names */                @Test        publicvoid  fetchtest () {            query Query=session.createquery ("from Dept D INNER join fetch d.emps");            List<Dept> list=query.list ();              for (Dept item:list) {                System.out.println (item.getdeptname ()+ "\ T" +Item.getemps (). iterator (). Next (). Getempname ());            }        } Copy Code

Batch processing of data in Hibernate

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.