HIbernate 大批量数据处理

节 1.01   HQL 更新 / 删除大批量数据

Transaction transaction = session .beginTransaction();

String hql = "UPDATE UserInfo user set user.username=:username,user.password=:password" ;

Query query = session .createQuery(hql);

query.setString(paramsName[0], paramsValue [0]);

query.executeUpdate();

transaction.commit();

注:使用 HQL 处理大批量数据会直接执行 DML 语句,从而绕过 Hibernate 的上下文和所有高速缓存。

节 1.02   HQL 创建大批量数据

Query q = session.createQuery( "INSERT INTO LostCreditCard(type,number) SELECT c.type,c.number FROM CreditCard c join c.user u" );

int createdObjects = q.executeUpdate();

 

节 1.03   批量更新数据

Hibernate.xml 文件中添加以下内容

< property name = "hibernate.jdbc.batch_size" > 20 property >

 

Session session = sessionFactroy.openSession();

Transaction tx = session.beginTransaction();

Query query = session.createQuery()

ScrollableResults cursor = query.scroll( "FROM SettleEnterRecord" ).scroll();

int count = 0;

while (cursor.next()) {

    SettleEnterRecord record = (SettleEnterRecord) cursor.get(0);

record.setIsValid( "2" );

if (++count % 100 == 0) {

              session.flush();

              session.clear();

           }

       }

tx.commit();

session.close();

节 1.04   批量插入数据

Session session = sessionFactroy.openSession();

Transaction tx = session.beginTransaction();

for ( int i = 0 ; i < 100000; i ++){

              Item item = new Item ();

              session.save(item);

              if (i%100 == 0){

                  session.flush ();

                  session.clear ();

              }

           }

tx.commit();

session.close ();

 

你可能感兴趣的:(ORM)