在Hibernate中处理批量更新和批量删除
批量更新是指在一個事務中更新大批量數據,批量刪除是指在一個事務中刪除大批量數據。以下程序直接通過Hibernate API批量更新CUSTOMERS表中年齡大于零的所有記錄的AGE字段: 如果CUSTOMERS表中有1萬條年齡大于零的記錄,那么Session的find()方法會一下子加載1萬個Customer對象到內存。當執行tx.commit()方法時,會清理緩存,Hibernate執行1萬條更新CUSTOMERS表的update語句:
view plaincopy to clipboardprint?
update CUSTOMERS set AGE=? …. where ID=i;?? update CUSTOMERS set AGE=? …. where ID=j;?? ……?? update CUSTOMERS set AGE=? …. where ID=k;?? update CUSTOMERS set AGE=? …. where ID=i;update CUSTOMERS set AGE=? …. where ID=j;……update CUSTOMERS set AGE=? …. where ID=k;
以上批量更新方式有兩個缺點: (1)占用大量內存,必須把1萬個Customer對象先加載到內存,然后一一更新它們。
(2)執行的update語句的數目太多,每個update語句只能更新一個Customer對象,必須通過1萬條update語句才能更新一萬個Customer對象,頻繁的訪問數據庫,會大大降低應用的性能。為了迅速釋放1萬個Customer對象占用的內存,可以在更新每個Customer對象后,就調用Session的evict()方法立即釋放它的內存:
view plaincopy to clipboardprint?
tx = session.beginTransaction();?? Iterator customers=session.find("from Customer c where c.age>0").iterator();?? while(customers.hasNext()){?? Customer customer=(Customer)customers.next();?? customer.setAge(customer.getAge()+1);?? session.flush();?? session.evict(customer);?? }????tx.commit();?? session.close();?? tx = session.beginTransaction();Iterator customers=session.find("from Customer c where c.age>0").iterator();while(customers.hasNext()){Customer customer=(Customer)customers.next();customer.setAge(customer.getAge()+1);session.flush();session.evict(customer);} tx.commit();session.close();
在以上程序中,修改了一個Customer對象的age屬性后,就立即調用Session的flush()方法和evict()方法,flush()方法使Hibernate立刻根據這個Customer對象的狀態變化同步更新數據庫,從而立即執行相關的update語句;evict()方法用于把這個Customer對象從緩存中清除出去,從而及時釋放它占用的內存。 但evict()方法只能稍微提高批量操作的性能,因為不管有沒有使用evict()方法,Hibernate都必須執行1萬條update語句,才能更新1萬個Customer對象,這是影響批量操作性能的重要因素。假如Hibernate能直接執行如下SQL語句: update CUSTOMERS set AGE=AGE+1 where AGE>0; 那么,以上一條update語句就能更新CUSTOMERS表中的1萬條記錄。但是Hibernate并沒有直接提供執行這種update語句的接口。應用程序必須繞過Hibernate API,直接通過JDBC API來執行該SQL語句:
view plaincopy to clipboardprint?
tx = session.beginTransaction();?? Connection con=session.connection();?? PreparedStatement stmt=con.prepareStatement("update CUSTOMERS set AGE=AGE+1 "??+"where AGE>0 ");?? stmt.executeUpdate();?? tx.commit();?? tx = session.beginTransaction();Connection con=session.connection();PreparedStatement stmt=con.prepareStatement("update CUSTOMERS set AGE=AGE+1 "+"where AGE>0 ");stmt.executeUpdate();tx.commit();
以上程序演示了繞過Hibernate API,直接通過JDBC API訪問數據庫的過程。應用程序通過Session的connection()方法獲得該Session使用的數據庫連接,然后通過它創建PreparedStatement對象并執行SQL語句。值得注意的是,應用程序仍然通過Hibernate的Transaction接口來聲明事務邊界。
轉載于:https://www.cnblogs.com/soundcode/archive/2010/12/20/1911941.html
總結
以上是生活随笔為你收集整理的在Hibernate中处理批量更新和批量删除的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 为何中国大陆的电视剧的集数,需要考虑受限
- 下一篇: [解决]eclipse中android自