---
title: "Hibernate的批量操作"
author: "gu6866"
date: "2012-09-20T21:38:39Z"
tags: []
categories: ["开源软件"]
slug: "hibernate"
draft: false
lastmod: "2012-09-20T21:38:39Z"
id: 1682602
url: "https://premier9527.iteye.com/blog/1682602"
---

**批量插入（Batch inserts）**

如果要将很多对象持久化，你必须通过经常的调用 `flush()` 以及稍后调用 `clear()` 来控制第一级缓存的大小,防止`内存溢出异常`。

 

Session session = sessionFactory.openSession();  
Transaction tx = session.beginTransaction();  
    
ScrollableResults users = session.getNamedQuery("GetUsers")  
    .setCacheMode(CacheMode.IGNORE)  
    .scroll(ScrollMode.FORWARD\_ONLY);  
int count=0;  
while ( users.next() ) {  
    User user= (User) users.get(0);  
    user.updateStuff(...);  
    if ( ++count % 20 == 0 ) {  
        //flush a batch of updates and release memory:  
        session.flush();  
        session.clear();  
    }  
}

    
tx.commit();  
session.close();

 

 

 

**批量更新(Batch update)**

此方法同样适用于检索和更新数据。此外，在进行会返回很多行数据的查询时， 你需要使用 `scroll()` 方法以便充分利用服务器端游标所带来的好处。

 

Session session = sessionFactory.openSession();  
Transaction tx = session.beginTransaction();  
    
ScrollableResults users = session.getNamedQuery("GetUsers")  
    .setCacheMode(CacheMode.IGNORE)  
    .scroll(ScrollMode.FORWARD\_ONLY);  
int count=0;  
while ( users.next() ) {  
    User user= (User) users.get(0);  
    user.updateStuff(...);  
    if ( ++count % 20 == 0 ) {  
        //flush a batch of updates and release memory:  
        session.flush();  
        session.clear();  
    }  
}

    
tx.commit();  
session.close();