Hibernate 消極式載入和立即載入

來源:互聯網
上載者:User

標籤:

概念

什麼是消極式載入:所謂消極式載入就是當在真正需要資料的時候,才真正執行資料載入操作。可以簡單理解為,只有在使用的時候,才會發出sql語句進行查詢,資料是分N次讀取。

什麼是立即載入:所謂立即載入既是所有的相關資料一次被讀取出來,而不是分N次。

一、消極式載入:NHibernate消極式載入須有Session存在,且配置為Lazy=true(預設)

DAL中編寫方法如下:

        //消極式載入

        public Order LazyLoad()

        {

            //返回order對象後ISession將繼續存在

            return session.Get<Order>(2);

           

            //返回order後ISession將會立即被銷毀

            //using (ISession iSession = new SessionManager().GetSession())

            //{

            //    Order order = iSession.Get<Order>(2);

            //    return order;

            //}

        }

上面有兩種返回order對象的方式,一種返回order後session繼續存在,一種在返回order後session就被銷毀了,我們先使用未被注釋的方法,然後使用被注釋了的代碼。

 

DAL.Test中編寫如下方法:

        [Test]

        public void LazyLoadTest()

        {

            Order order = sample.LazyLoad();

        }

然後設定斷點,進行測試調試,在即時視窗編寫代碼測試。

 

當返回order後session繼續存在時,結果如下:

order.OrderDate.ToString()

"2009-10-17 11:22:46"

order.Customer.Firstname

"soldier"

order.Products.Count

2

這裡可以看到,我們可以訪問order對象的關聯對象Customer和Products

 

當返回order後session立即被銷毀時,結果如下:

order.OrderDate.ToString()

"2009-10-17 11:22:46"

order.Customer.Firstname

“order.Customer.Firstname”引發了“NHibernate.LazyInitializationException”類型的異常

    base {NHibernate.HibernateException}: {"Initializing[Model.Entities.Customer#2]-Could not initialize proxy - no Session."}

    EntityId: 2

    EntityName: "Model.Entities.Customer"

order.Products.Count

“order.Products.Count”引發了“NHibernate.LazyInitializationException”類型的異常

    base {NHibernate.HibernateException}: {"Initializing[Model.Entities.Order#2]-failed to lazily initialize a collection of role: Model.Entities.Order.Products, no session or session was closed"}

    EntityId: 2

    EntityName: "Model.Entities.Order"

這裡我們可以訪問order對象,這是理所當然的。但是不論我訪問order的關聯對象Customer還是Products時,都會報“NHibernate.LazyInitializationException”異常,因為訪問時使用的是消極式載入,但是session此時已經被銷毀了,所以報錯,這說明要使用消極式載入就必須保證session是存在的。

 

二、立即載入:有三種方法進行立即載入,一、配置lazy=”false”;二、使用NHibernateUtil類;三、使用帶fetch的HQL語句

1)       配置lazy=”false”進行立即載入

首先修改order.hbm.xml檔案,將

<bag name="Products" generic="true" table="OrderProduct">

修改為如下:

<bag name="Products" generic="true" table="OrderProduct" lazy="false">

然後再測試,結果如下:

order.OrderDate.ToString()

"2009-10-17 11:22:46"

order.Products.Count

2

order.Customer.Firstname

“order.Customer.Firstname”引發了“NHibernate.LazyInitializationException”類型的異常

    base {NHibernate.HibernateException}: {"Initializing[Model.Entities.Customer#2]-Could not initialize proxy - no Session."}

    EntityId: 2

    EntityName: "Model.Entities.Customer"

這裡可以看到配置了lazy="false"的Products可以訪問,因為它的資料已經和order一起讀取了,但是當我們訪問Customer時,報出了上面我們曾經見到過的錯誤,因為在order的對應檔裡並沒有配置Customer為立即載入,所以報錯。

 

2)       使用NHibernateUtil類進行強制立即載入

首先修改LazyLoad()函數的代碼如下:

            //返回order後ISession將會立即被銷毀

            using (ISession iSession = new SessionManager().GetSession())

            {

                Order order = iSession.Get<Order>(2);

                NHibernateUtil.Initialize(order.Customer);                   //這裡強制立即載入order的關聯Customer對象

                return order;

            }

測試結果如下:

order.OrderDate.ToString()

"2009-10-17 11:22:46"

order.Products.Count

2

order.Customer.Firstname

"soldier"

哈哈,又可以訪問Customer對象了。

 

3)       使用帶fetch的HQL查詢

a) 使用HQL查詢方法也可以立即載入。HQL語句支援的連線類型為:inner join(內串連)、left outer join(左外串連)、right outer join(右外串連)、full join(全串連,不常用)。

b) “抓取fetch”串連允許僅僅使用一個選擇語句就將相關聯的對象隨著他們的父物件的初始化而被初始化,可以有效代替了對應檔中的外聯結與延遲屬性聲明。

 

幾點注意:

c) fetch不與setMaxResults() 或setFirstResult()共用,因為這些操作是基於結果集的,而在預先抓取集合時可能包含重複的資料,也就是說無法預Crowdsourced Security Testing道精確的行數。

d) fetch還不能與獨立的with條件一起使用。通過在一次查詢中fetch多個集合,可以製造出笛卡爾積,因此請多加註意。對多對多映射來說,同時join fetch多個集合角色可能在某些情況下給出並非預期的結果,也請小心。

e)使用full join fetch 與 right join fetch是沒有意義的。 如果你使用屬性層級的延遲擷取,在第一個查詢中可以使用 fetch all properties 來強制NHibernate立即取得那些原本需要消極式載入的屬性。

 

刪除order.hbm.xml中的lazy="false"屬性設定,這樣order的Products就不是立即載入了,並將LazyLoad()函數修改如下:

        //消極式載入

        public Order LazyLoad()

        {

            //返回order對象後ISession將繼續存在

            //return session.Get<Order>(2);

           

            //返回order後ISession將會立即被銷毀

            //using (ISession iSession = new SessionManager().GetSession())

            //{

            //    Order order = iSession.Get<Order>(2);

            //    NHibernateUtil.Initialize(order.Customer);

            //    return order;

            //}

 

            //使用HQL的fetch進行立即載入

            using (ISession iSession = new SessionManager().GetSession())

            {

                return iSession.CreateQuery("from Order o left join fetch o.Products where o.OrderId=2 ")

                    .UniqueResult<Order>();

            }

        }

調試測試結果如下:

order.OrderDate.ToString()

"2009-10-17 11:22:46"

order.Products.Count

2

order.Customer.Firstname

“order.Customer.Firstname”引發了“NHibernate.LazyInitializationException”類型的異常

    base {NHibernate.HibernateException}: {"Initializing[Model.Entities.Customer#2]-Could not initialize proxy - no Session."}

    EntityId: 2

    EntityName: "Model.Entities.Customer"

在上面的HQL語句中通過fetch o.Products語句來立即載入Products,所以測試裡可以訪問Products,而訪問Customer時,則出錯了。

 

然後我們修改上面的HQL語句:

"from Order o left join fetch o.Products where o.OrderId=2 "

為如下

"from Order o left join fetch o.Products inner join fetch o.Customer where o.OrderId=2 "

 

並再進行同上面一樣的測試看結果如何,我的如下:

order.OrderDate.ToString()

"2009-10-17 11:22:46"

order.Products.Count

2

order.Customer.Firstname

"soldier"

Hibernate 消極式載入和立即載入

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.