Hibernate中一級緩衝概念以及flush與clear的區別

來源:互聯網
上載者:User

標籤:min   sys   hibernate   需要   行記錄   span   setname   請求   tag   

Hibernate採用緩衝機制提高資料查詢效率。緩衝分為一級緩衝和二級緩衝,一級緩衝在Session中存在,二級緩衝需要手動設定。

在一級緩衝中,如果資料儲存到資料庫中後,而session又沒有關閉的話,那麼這些資料會放到緩衝中,再次發出查詢請求,Hibernate首先檢查緩衝中是否有該資料,如果找到該資料,那麼就不會向資料庫發起查詢請求而是直接將緩衝中的資料取出。請看下面的例子:

public class Main{    public static void main(String[] args) throws Exception    {        Member member = (Member)HibernateSessionFactory.getSession().get(Member.class, 7);        System.out.println(member);                  Member member1 = (Member)HibernateSessionFactory.getSession().get(Member.class, 7);        System.out.println(member1);    }}

上面的代碼實際上只向資料庫發起了一次查詢請求:

Hibernate:     select        member0_.mid as mid0_0_,        member0_.age as age0_0_,        member0_.birthday as birthday0_0_,        member0_.name as name0_0_,        member0_.note as note0_0_,        member0_.salary as salary0_0_     from        hedb.member member0_     where        member0_.mid=?Member [mid=7, age=22, birthday=2017-01-10, name=admin, note=Good person!, salary=22.22]Member [mid=7, age=22, birthday=2017-01-10, name=admin, note=Good person!, salary=22.22]

這樣的機制會大大提高查詢效率。

但是!如果說現在要求你批量儲存100000行記錄呢?按照此時的道理來講,這100000行記錄都要緩衝起來,這樣明顯會造成一個非常危險的舉動,所以在進行實際的開發過程之中,必須要考慮資料的分批處理。

請看下面的代碼:

 1     public static void main(String[] args) throws Exception 2     { 3         for (int x = 100; x < 10000; x++) 4         { 5             Member vo = new Member(); 6             vo.setName("你好"); 7             vo.setAge(20); 8             vo.setSalary(1000.0); 9             vo.setBirthday(new Date());10             HibernateSessionFactory.getSession().save(vo);11             if (x % 10 == 0)12             {13                 // 每10條記錄進行一次緩衝區的重新整理14                 HibernateSessionFactory.getSession().flush();15                 HibernateSessionFactory.getSession().clear(); 17             }18         }19 20         HibernateSessionFactory.getSession().beginTransaction().commit();21     }

上面用到了Session介面的flush()和clear()函數。

  • flush()是將緩衝中的所有資料全部提交到資料庫中,也就是將緩衝中暫未儲存到資料庫的資料儲存到資料庫中。
  • clear()是將緩衝全部清空。

Hibernate中一級緩衝概念以及flush與clear的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.