標籤:
Hibernate批量處理
一 批量插入
將很多條記錄插入資料庫時,Hibernate通常會採用以下做法:
public void test() {
for(int i=0;i<1000;i++){
Person p =new Person("admin"+i,1234+i,new Date());
session.persist(p);
System.out.println(p);
}
}
但是隨著這個程式的運行,會在某個時刻失敗,並拋出OutOfMemoryException,這是因為Hibernate的Session持有一個必選的一級緩衝,所有的Person執行個體都將在這個Session層級的緩衝區存放。
解決方案:定時將Session緩衝的資料刷入資料庫。
public void test() {
for(int i=0;i<1000;i++){
Person p =new Person("admin"+i,1234+i,new Date());
session.persist(p);
if(i%10==0){
session.flush(); //可以立即同步持久化狀態資料到資料庫表
session.clear();
}
System.out.println(p);
}
tx.commit();
}
二 批次更新
上面的方法依然適用,應該使用scroll()方法,從而充分利用伺服器端遊標所帶來的效能優勢。
public class myTest {
public static void main(String[] args) {
Configuration config=new Configuration().configure();
SessionFactory factory=config.buildSessionFactory();
Session session=factory.openSession();
Transaction tx=session.beginTransaction();
ScrollableResults persons=session.createQuery("from Person")
.setCacheMode(CacheMode.IGNORE)
.scroll(ScrollMode.FORWARD_ONLY);
int count=0;
while(persons.next()){
Person p=(Person) persons.get(0);
p.setName("name:"+count);
if(++count%10==0){
session.flush();
session.clear();
}
}
tx.commit();
session.close();
}
}
但是這種方式效率不高,因為要先執行查詢語句,在執行資料更新。為了避免這種情況,Hibernate提供了一種類似於DML語句的批次更新、大量刪除的HQL文法。
三 DML風格的批次更新/刪除
文法格式:
update | delete from? <ClassName> [where where_conditions]
注意:from關鍵字可選,from自置中只能有一個類名,可以在該類名後指定別名。不能在批量HQL語句中使用串連,顯式或隱式的都不行,但可以在where子句中使用子查詢。
public class myTest {
public static void main(String[] args) {
Configuration config=new Configuration().configure();
SessionFactory factory=config.buildSessionFactory();
Session session=factory.openSession();
Transaction tx=session.beginTransaction();
String hqlUpdate="update Person p set name= :newName"; //刪除可以改為String hqlDelete="delete Person";即可
int updateEntities=session.createQuery(hqlUpdate)
.setString("newName","新名字")
.executeUpdate();
tx.commit();
session.close();
}
}
大量刪除:
public class myTest {
public static void main(String[] args) {
Configuration config=new Configuration().configure();
SessionFactory factory=config.buildSessionFactory();
Session session=factory.openSession();
Transaction tx=session.beginTransaction();
String hqlDelete="delete Person";
int updateEntities=session.createQuery(hqlDelete)
.executeUpdate();
tx.commit();
session.close();
}
}
Hibernate五 批量處理