Batch Processing of Hibernate-Batch update

Source: Internet
Author: User

Private void updateUsers () throws Exception
{
// Open the Session
Session session = HibernateUtil. currentSession ();
// Start the transaction
Transaction tx = session. beginTransaction ();
// Query all records in the User table
ScrollableResults users = session. createQuery ("from User ")
. SetCacheMode (CacheMode. IGNORE)
. Scroll (ScrollMode. FORWARD_ONLY );
Int count = 0;
// Traverse all records in the User table
While (users. next ())
{
User u = (User) users. get (0 );
U. setName ("new username" + count );
// When count is a multiple of 20,
// Flush the update result from the Session to the database.
If (++ count % 20 = 0)
{
Session. flush ();
Session. clear ();
}
}
Tx. commit ();
HibernateUtil. closeSession ();
}
In this way, although batch update can be executed, the effect is very poor. If the execution efficiency is not high, you need to first execute Data Query and then execute data update. In addition, this update will be a row-by-row update, that is, each row of Record update needs to execute an update statement, performance is also very low.
To avoid this situation, Hibernate provides a HQL syntax similar to DML statements for batch update and batch deletion.
Author: fkJava Li Gang

Related Article

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.