Hibernate3 batch update and delete data

Source: Internet
Author: User

Hibernate3.0 uses the new anlr-based hql/SQL query translator. In the hibernate configuration file, the hibernate. query. factory_class attribute is used to select the query translator.
(1) Select the query translator of hibernate3.0:
Hibernate. query. factory_class = org. hibernate. hql. Ast. astquerytranslatorfactory
(2) Select the query translator for hibernate2.1.
Hibernate. query. factory_class = org. hibernate. hql. Classic. classicquerytranslatorfactory
To use the 3.0 batch update and delete functions, you can only select (1). Otherwise, you cannot explain the batch update statements. Select (2) but cannot explain the batch update statement.

Bulk update/delete)

As has been discussed, automatic and transparent object/relationship ing focuses on the state of management objects. This means that the object status exists in the memory. Therefore, directly updating or deleting the data in the database (using SQL statement update and delete) will not affect the object status and object data in the memory. However, Hibernate provides the Hibernate query language to execute a large number of SQL-style (update) and (delete) statements.

The syntax of the update and delete statements is: (update | delete) from? Classname (where where_conditions )?. There are several notes:

In the from clause (from-clause), The from keyword is optional.

There can be only one class name in the from clause (from-clause), and it cannot have aliases

You cannot use connections in a large number of hql statements (explicit or implicit connections are not supported ). However, subqueries can be used in the WHERE clause.

The entire WHERE clause is optional.

For example, use query.exe cuteupdate () to execute an hql update statement:

 

Session session = sessionfactory. opensession ();

Transaction Tx = session. begintransaction ();

String hqlupdate = "Update customer set name =: newname where name =: oldname ";

Int updatedentities = S. createquery (hqlupdate). setstring ("newname", newname). setstring ("oldname", oldname). executeupdate (); Tx. Commit ();

Session. Close ();

Execute an hql Delete statement and use the query.exe cuteupdate () method (this method is set for those familiar with JDBC preparedstatement.exe cuteupdate)

 

Session session = sessionfactory. opensession ();

Transaction Tx = session. begintransaction ();

String hqldelete = "delete customer where name =: oldname ";

Int deletedentities = S. createquery (hqldelete). setstring ("oldname", oldname). executeupdate ();

TX. Commit ();

Session. Close ();

The integer value returned by query.exe cuteupdate () indicates the number of records affected by this operation. Note that this value may be related to the number of rows affected by the database (the last SQL statement) or not. A large number of hql operations may result in the execution of multiple actual SQL statements. For example, this operation is performed on classes mapped by joined-subclass. The returned value indicates the number of records affected by the statement. In the joined-subclass example, deleting a subclass may not only delete the table mapped to the subclass, but also affect the "root" table, it may also affect the tables of child classes mapped to the inherited joined-subclass method.

 

Bytes ------------------------------------------------------------------------------------------------

 

I used it in spring + hibernate

String SQL = "delete planpackagerelations where ppfid =" + ppfid;
Int A = this.gethibernatetemplate().getsessionfactory().opensession().createquery(sqlcmd.exe cuteupdate ();
The result console outputs the following information:

Shared connection mcwrapper ID 19911991 managed connection com. IBM. ws. rsadapter. SPI. wsrdbmanagedconnectionimpl @ 12781278 state: state_tran_wrapper_inuse

 

Bytes -------------------------------------------------------------------------------------------------

 

Call JDBC to delete data based on non-primary keys.

/**
* Delete planpackagerelations Based on ppfid.
* @ Param ppfid
*/
Public void deleteplanpackagerelations (string ppfid ){
Final string ppfidfinal = ppfid;
Try {

This.gethibernatetemplate(cmd.exe cute (New hibernatecallback (){
Public object doinhibernate (session) throws hibernateexception, sqlexception {
List result = new arraylist ();
String SQL = "delete planpackagerelations where ppfid =: ppfid ";
Query query = session. createquery (SQL). setstring ("ppfid", ppfidfinal );
Result. Add (New integer(query.exe cuteupdate ()));
Return result;
}

});

// String SQL = "delete planpackagerelations where ppfid =" + ppfid;
// Int A = this.gethibernatetemplate().getsessionfactory().opensession().createquery(sqlcmd.exe cuteupdate ();
//

} Catch (dataaccessexception t ){
T. printstacktrace ();
Throw T;
} Catch (exception e ){
E. printstacktrace ();
}
}

Bytes --------------------------------------------------------------------------------------------

 

Use Hibernatetemplate BatchDelete data

In the spring + Hibernate frameworkHibernatetemplateTo use hibernate,Hibernatetemplate
The bulkupdate () of cannot be dynamic.BatchDelete, that is, when using bulkuplate, you must first determine the Placeholder "? ", And then use its overload method bulkupdate (querystring, object []). At this time, the number of elements in object [] must be the same as the Placeholder"? "In querystring. So you can use the hibernatecallback callback function for dynamicBatchDelete, that is, the number of elements to be deleted is not considered. The usage is as follows:
Public void bulkdelete (final object [] IDs) throws exception {
Final string querystring = "delete persistentmodel where ID in (: IDS )";
Super.exe cute (New hibernatecallback (){
Public object doinhibernate (session) throws hibernateexception, sqlexception {
Query query = session. createquery (querystring );
Query. setparameterlist ("IDS", IDS );
Return query.exe cuteupdate ();
}
});
}
Note: add () to the placeholder in the red; otherwise, a syntax error is thrown.

 

Bytes -----------------------------------------------------------------------------------------

Bulkupdate usage:

 

String updatesql = "Update rsceref ref set ref. rulecode =? Where ref. rscerefcode =? ";
Gethibernatetemplate (). bulkupdate (updatesql, new object [] {chkobj. getbmcrcode (), listexistrulesql. Get (0 )});

 

This. gethibernatetemplate (). bulkupdate (SQL );

 

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.