Hibernate batch processing data, HQL connection query

Source: Internet
Author: User
Tags bulk insert

First, batch processing operations

Bulk processing of data is 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) Use HQL The database level for bulk operations

(2) Use JDBC API for bulk operations database level

(3) Use Session for batch operations will go into cache

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. using JDBC  api Bulk operations

in the in Hibernate applications , use the JDBC API to bulk execute insert, modify, and DELETE statements using the doWork of the Session Method Execution The action specified by the work object, that is, the Execute () method that invokes 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!!!"); }

Implementation results:

3. Implement the session for batch operation

Use The Session object handles a large number of persisted objects, and the objects that are processed and no longer accessed are emptied from the cache in a timely manner. 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!!"); }

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

 /*   * Connect Employee-affiliated departments  */  @Test  public  void   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 statements, if the Emp class is assigned an alias of "E", it can be accessed through the form of e.dept.deptname Dept object that Deptname property. 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 ());            }        }

Output Result:

Hibernate batch processing data, HQL connection query

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.