Hibernate batch Operations

Source: Internet
Author: User
Tags aliases bulk insert


Batch processing of data: refers to the need to process a large amount of data in a transactional scenario.
How hibernate processes data in batches:
1. Using HQL for bulk operations: HQL is cross-database, object-oriented, but has limitations, can only be used for a single persisted class, does not support connections, and cannot use subqueries
2. Using the JDBC API for bulk operations: simple operation, the ability to use different database features in SQL
3. Use session for bulk operations: Load relational data into in-memory operations and require code to handle complex business logic
Use HQL for bulk operations:
1.HQL can query data, BULK INSERT and update and delete data, actually completed in the database, processed data is not loaded into the session cache.
HQL statement for inserting, updating, and deleting operations using the Executeupdate () method of the query interface
First you need Sessionutil.java:
Import Org.hibernate.Query;
Import org.hibernate.Session;
Import org.hibernate.Transaction;
Import db. Hibernatesessionfactory;
public class Sessionutil {
protected Session session=null;
protected query query = NULL;
protected Transaction tx= null;
Public Session getsession () {
return Hibernatesessionfactory.getsession ();
}
public void CloseSession () {
Hibernatesessionfactory.closesession ();
}
}
Ps:sessionutil needs to include Hibernatesessionfactory.java, which is automatically generated in the Hibernate import jar package.
A. Bulk add operations: addmanyentity (list<entity> List)
Main code:
/**
* [addmanyentity: Batch add, entity belongs to physical class]
GetSession (): Get session
BeginTransaction (): Transaction start
Commit (): Transaction commit
Rollback (): Error rollback
* @param {[traverse with List collection]} list<entity> list
*/
public void addmanyentity (list<entity> List) {
try {
Session=getsession ();
Tx=session.begintransaction ();
for (Entity entity:list) {
Session.save (entity);
}
Tx.commit ();
SYSTEM.OUT.PRINTLN ("Operation succeeded! ");
} catch (Exception e) {
E.printstacktrace ();
Tx.rollback ();
System.out.println ("The operation failed! ");
}
finally{
CloseSession ();
}
}
B. Batch modification: updatemanyentity (data type attribute 1, data Type Property 2)
Main code:
/**
* [updatemanyentity Batch modification]
* @param {The data type of the property of the entity class is determined]} data Type property 1 [Properties of entity class]
* @param {The data type of the property of the entity class is determined]} data Type property 2 [Properties of entity class]
*/
public void updatemanyentity (data Type property 1, Data Type property 2) {
String hql= "Update entity class Name set Property name =: Property name where Property name =: attribute name";
try {
Session=getsession ();
Tx=session.begintransaction ();
Query=session.createquery (HQL);
Query.setparameter ("attribute 1", attribute 1);
Query.setparameter ("attribute 2", attribute 2);
int num=query.executeupdate ();
System.out.print ("Modified data:" +num);
Tx.commit ();
SYSTEM.OUT.PRINTLN ("Operation succeeded! ");
} catch (Exception e) {
E.printstacktrace ();
Tx.rollback ();
System.out.println ("The operation failed! ");
}
finally{
CloseSession ();
}
}
C. Bulk Delete: deletemanyentity (data type attribute 1)
Main code:
/**
* [deletemanyentity Batch Delete]
* @param {The data type of the attribute with the entity class is determined]} data type property [usually deleted by primary key]
*/
public void deletemanyentity (data type property) {
String hql= "Delete from entity class name where property name =: attribute name";
try {
Session=getsession ();
Tx=session.begintransaction ();
Query=session.createquery (HQL);
Query.setparameter ("Attributes", attributes);
int num=query.executeupdate ();
System.out.print ("Deleted data is:" +num);
Tx.commit ();
SYSTEM.OUT.PRINTLN ("Operation succeeded! ");
} catch (Exception e) {
E.printstacktrace ();
Tx.rollback ();
System.out.println ("The operation failed! ");
}
finally{
CloseSession ();
}
}
Use the JDBC API for bulk operations:
1. Batch update:
/**
* [updateentity Batch UPDATE]
* 1. You need to use the DoWork (work) method of the session to perform the operation specified by the work object, that is, the method of calling execute ()
* 2.Session Pass the current database connection to the Execute () method
*
*/
public void updateentity (data Type property 1, Data Type property 2) {
Final String sql= "Update table name set property =?" where property =? ";
try {
Session=getsession ();
Tx=session.begintransaction ();
Work work=new () {
@Override
public void execute (Connection Connection) throws SQLException {
PreparedStatement preparedstatement=connection.preparestatement (SQL);
Preparedstatement.setstring (1, attributes);
Preparedstatement.setint (2, attributes);
Preparedstatement.executeupdate ();
}
};
Session.dowork (work);
Tx.commit ();
SYSTEM.OUT.PRINTLN ("Operation succeeded! ");
} catch (Exception e) {
E.printstacktrace ();
Tx.rollback ();
System.out.println ("The operation failed! ");
}
finally{
CloseSession ();
}
}
2. Bulk Delete
/**
* [deleteentity Batch Delete]
* 1. You need to use the DoWork (work) method of the session to perform the operation specified by the work object, that is, the method of calling execute ()
* 2.Session Pass the current database connection to the Execute () method
*
*/
public void deleteentity (data Type property 1, Data Type property 2) {
Final String sql= "Delete Table name where property =?";
try {
Session=getsession ();
Tx=session.begintransaction ();
Work work=new () {
@Override
public void execute (Connection Connection) throws SQLException {
PreparedStatement preparedstatement=connection.preparestatement (SQL);
Preparedstatement.setstring (1, attributes);
Preparedstatement.executeupdate ();
}
};
Session.dowork (work);
Tx.commit ();
SYSTEM.OUT.PRINTLN ("Operation succeeded! ");
} catch (Exception e) {
E.printstacktrace ();
Tx.rollback ();
System.out.println ("The operation failed! ");
}
finally{
CloseSession ();
}
}
3. Batch query: Findallentity ()
Main code:
/**
* [findallentity Batch query]
* 2 ways to iterate through the collection:
* 1.object[] Array: list<object[]>list=query.list ();
Query=session.createsqlquery (SQL);
List<object[]>list=query.list ();
For (object[] objects:list) {
for (Object object:objects) {
System.out.print (object+ "\ t");
}
System.out.println ("");
}
* 2. Form of entity class: List<entity>list=query.list ();
* Query=session.createsqlquery (SQL). addentity (Entity.class);
List<entity>list=query.list ();
for (Entity entity:list) {
System.out.println (Entity.getxx ());
}
*
*
*/
public void findallentity () {
String sql= "Select *from student";
try {
Session=getsession ();
First type: object[]
/*query=session.createsqlquery (SQL);
List<object[]>list=query.list ();
For (object[] objects:list) {
for (Object object:objects) {
System.out.print (object+ "\ t");
}
System.out.println ("");
}*/
Second type: entity class
Query=session.createsqlquery (SQL). addentity (Entity.class);
List<entity>list=query.list ();
for (Entity entity:list) {
System.out.println (Entity.getxx ());
}
System.out.println (List.size ());
SYSTEM.OUT.PRINTLN ("Operation succeeded! ");
} catch (Exception e) {
E.printstacktrace ();
System.out.println ("The operation failed! ");
}
finally{
CloseSession ();
}
}
3. Conditional query:
/**
*
*
* Addentity (alias "Aliases 1", Entityclass "entity class")
* AddJoin (alias "Associated aliases", path "attribute of alias 1")
* {}: Gets the property name corresponding to the alias
* Alias. *: Gets all the attributes under the alias name
*/
public void Findentitybyxx () {
String sql= "Select {alias 1.*},{alias 2.*} from table name 1 alias 1 inner JOIN table name 2 alias 2 on alias 1. Field name = Alias 2. Field name";
try {
Session=getsession ();
Query=session.createsqlquery (SQL). Addentity ("Alias", Entity.class). AddJoin ("Alias", "Alias. Table Name 2");
List list=query.list ();
System.out.println (List.size ());
} catch (Exception e) {
E.printstacktrace ();
}
finally{
CloseSession ();
}
4. Name the query:
Need to be in Entity.hbm.xml:
<query name= "Custom: GetEntity" >
<! [cdata[
HQL statements
]]>
</query>
Main code:
/**
* 1. The first way: non-conditional query: Query=session.getnamedquery ("getentity");
* 2. The second type: Conditional query: query.setparameter ("attribute name", "condition");
*
*/
public void Getentityxx () {
try {
Session=getsession ();
Query=session.getnamedquery ("getentity");
Query.setparameter ("attribute name", "condition");
List<entity>list=query.list ();
for (Entity entity:list) {
System.out.println (Entity.getxx ());
}
} catch (Exception e) {
E.printstacktrace ();
}
finally{
CloseSession ();
}
}
Use session for bulk operations:
Objects that have been processed and are no longer reachable need to be purged from the cache in a timely manner:
First: Call the Flush () method to force the synchronization of the cache and database: Session.flush ();
Then: Call the Clear () method to empty the cache: Session.clear ();

This article is from the "mastiffs" blog, make sure to keep this source http://7917260.blog.51cto.com/7907260/1751516

Hibernate batch Operations

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.