Hibernate batch processing data

Source: Internet
Author: User

01. BULK INSERT Data

Step ONE. Create Entity classes, Dept and EMP

  

/** * Employee class * @author Administrator * */public class Emp {    private Integer empId;    Private String empname;    Private Dept Dept;    Public Integer getempid () {        return empId;    }    public void Setempid (Integer empId) {        this.empid = empId;    }    Public String getempname () {        return empname;    }    public void Setempname (String empname) {        this.empname = empname;    }    Public Dept getdept () {        return Dept;    }    public void setdept (Dept Dept) {        this.dept = Dept;    }    }
/* * Department entity Class */public class Dept {    //don't ask the label    private Integer deptNo;    Private String deptname;    Associate a collection of employees    private set<emp> emps=new hashset<emp> ();        Public set<emp> getemps () {        return emps;    }    public void Setemps (set<emp> emps) {        this.emps = emps;    }    Public Integer Getdeptno () {        return deptNo;    }    public void Setdeptno (Integer deptNo) {        this.deptno = deptNo;    }    Public String getdeptname () {        return deptname;    }    public void Setdeptname (String deptname) {        this.deptname = deptname;    }    }

Step two: Create the Dept.hbm.xml and Emp.hbm.xml small configuration files

<!--dept.hbm.xml--><?xml version= "1.0"? ><! DOCTYPE hibernate-mapping public     "-//hibernate/hibernate mapping DTD 3.0//en"    "HTTP://WWW.HIBERNATE.ORG/DTD /HIBERNATE-MAPPING-3.0.DTD ">
<!--emp.hbm.xml--><?xml version= "1.0"? ><! DOCTYPE hibernate-mapping public     "-//hibernate/hibernate mapping DTD 3.0//en"    "HTTP://WWW.HIBERNATE.ORG/DTD /HIBERNATE-MAPPING-3.0.DTD ">

Step Three. Create a large profile hibernate.cfg.xml

<?xml version= ' 1.0 ' encoding= ' utf-8 '? ><! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "http://www.hibern ATE.ORG/DTD/HIBERNATE-CONFIGURATION-3.0.DTD ">

The above steps we do not do a detailed explanation, mainly look at the test code

/* use HQL statement to bulk process data */public class Hqlupdatedata    {     /* * * Bulk Add Data *    /@Test public    void Addtest ()    { C8/>session session=hibernateutil.getsession ();        Transaction tx=session.begintransaction ();        Query query = session.createquery ("insert into Dept (deptname) Select D.deptname| | D.deptno from Dept D where d.deptno>0 ");        int count = query.executeupdate ();        System.out.println (count);        Tx.commit ();        Hibernateutil.closesession ();    }

Bulk Operation via HQL

The HQL in Hibernate3 (Hibernate query language,hibernate query Language) not only retrieves data, it can also be used for bulk updates, deletions, and insertions of Data. Bulk operations are actually done directly in the database, and the processed data is not stored in the Session's cache, so it does not consume memory space.
The Query.executeupdate () method is similar to Preparedstatement.executeupdate () in the JDBC api, which executes HQL statements for updating, deleting, and inserting, while the latter executes for updates, Delete and insert the SQL Statement.

1. Batch Update data
The following program code demonstrates the bulk update of a customer object through Hql:
Session session = Sessionfactory.opensession ();
Transaction tx = Session.begintransaction ();

String hqlupdate =
"update Customer C set c.name =: newName where C.name =: oldname";
int updatedentities = Session.createquery (hqlupdate)
. setString ("newName", "Mike")
. setString ("oldname", "Tom")
. executeupdate ();

Tx.commit ();
Session.close ();
The SQL statement sent to the database by the above program code is:
Update CUSTOMERS set name= "Mike" where name= "Tom"

2. Bulk Delete Data
Session Delete () method deletes only one object at a time and is not suitable for bulk delete operations. The following program code demonstrates bulk deletion of the customer object through Hql:
Session session = Sessionfactory.opensession ();
Transaction tx = Session.begintransaction ();

String hqldelete = "delete Customer c where c.name =: oldname";
int deletedentities = session.createquery (hqldelete)
. setString ("oldname", "Tom")
. executeupdate ();
Tx.commit ();
Session.close ();
The SQL statement that the above program code submits to the database is:
Delete from CUSTOMERS where name= "Tom"

3. Bulk INSERT Data
The HQL syntax for inserting data is:
INSERT INTO EntityName properties_list select_statement
above EntityName represents the name of the persisted class, Properties_list represents a list of properties for a persisted class, and select_statement represents a subquery Statement.
HQL only supports insert INTO ... select ... The INSERT statement in the form, not the "insert into ... values ... "form the Insert Statement.
The following example shows how to bulk insert data through HQL. The Delinquentaccount and the customer classes are assumed to have both the ID and the name attribute, and the tables corresponding to these two classes are delinquent_accounts and customers tables, Respectively. The DelinquentAccount.hbm.xml and Customer.hbm.xml files are mapping files for these two classes, respectively. The following code can copy the data from the Customers table to the Delinquent_accounts table:
Session session = Sessionfactory.opensession ();
Transaction tx = Session.begintransaction ();

String Hqlinsert = "insert into Delinquentaccount (id, name) of select c.id, c.name from Customer C where c.id>1";
int createdentities = s.createquery (hqlinsert)
. executeupdate ();
Tx.commit ();
Session.close ();

The SQL statement submitted to the database by the program code above is:
INSERT into delinquent_accounts (id,name) select Id,name from CUSTOMERS where id>1

9.4.4 Bulk Operations directly through the JDBC API

When SQL insert, update, and DELETE statements are executed through the JDBC api, the data involved in the SQL statement is not loaded into memory. therefore, it does not occupy memory space.
The following program executes SQL statements for bulk updates directly through the JDBC Api:
Transaction tx = session.begintransaction ();
Obtain the database connection used by the session
Java.sql.Connection con=session.connection ();
Execute SQL statement for bulk update through the JDBC API
PreparedStatement stmt=con.preparestatement ("update CUSTOMERS set age=age+1"
+ " where Age>0 ");
Stmt.executeupdate ();

Tx.commit (); The

above program obtains the database connection used by the session through the connection () method of the session, and then creates the PreparedStatement object and executes the SQL statement through it. It is important to note that the application still declares the transaction boundary through Hibernate's transaction interface.
It is worth noting that in Hibernate3, although the connection () method of the session still exists, it has been deprecated and is not advocated, however, Hibernate3 provides an alternative: the Org.hibernate.jdbc.Work interface represents an operation to access the database directly through the JDBC api, and the Execute () method of the work interface is used to execute the direct JDBC API to access the Database:
public interface work {
//operation to access the database directly through the JDBC API
public void execute (Connection Connection) Throws SQLException; The DoWork method of the
}
session is used to perform the operation specified by the work object, called the Execute () method of the working Object. The session will pass the currently used database connection to the Execute () method.

The following program demonstrates the process of performing bulk operations through the work interface and the DoWork () method of the session:
Transaction tx=session.begintransaction ();
Defines an anonymous class that implements the work interface
work work=new work () {
public void execute (Connection Connection) throws sqlexception{
// Execute SQL statements for bulk updates using the JDBC API
PreparedStatement stmt=connection
. preparestatement ("update CUSTOMERS set age=age+1"
+ "where age>0");
Stmt.executeupdate ();
}
};

Perform work
Session.dowork (work);
Tx.commit ();

Hibernate batch processing data

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.