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