01-05-01-1 "Nhibernate (version 3.3.1.4000) in and out of the lake" delay loading and its class and set (set, bag, etc.) the effect of the combination of lazy attribute configuration on the Get and load methods

Source: Internet
Author: User

This article

Http://ayende.com/blog/3988/nhibernate-the-difference-between-get-load-and-querying-by-id

One of the more common mistakes that I see people doing with NHibernate isRelated to how they is loading entities by the primary key. This isbecause there is important differences between the three options. The most common mistake . is usingA query to the load by ID.inchparticular whenusingLinq forNHibernate.varCustomer = (    SelectCustomer fromS.linq<customer>()    whereCustomer. Id =customerIdSelectcustomer). FirstOrDefault (); Every time that I see something like that, I wince a little inside. The reason forThat isQuite simple. This isDoing a query by primary key. The key word here isa query. This means the database In   order to get a result   for this query. Unless you is using the query cache (which by default -won ' t),   thisForce  A query on the database, bypassing both the first level identity map and the second level cache. Get and Load is here forA reason, they provide a toGetAn entity by primary key. That isImportant forSeveral aspects, most importantly, it means that NHibernate can apply quite a few optimizations for  ThisProcess.

As if to say, do not use the primary key (by primary key) to query, because the primary key area query will bypass the first level and level two cache.

So we recommend using get and load to query

The following test is wrong, to see the correct conclusion of the coffin, please jump to:
Ultimate test:

--------------------------------------------

To implement lazy loading:

How to implement lazy loading:

To add lazy= "true" to the mapping file Xxx.hbm.xml of the class that implements the lazy load, there are two types of locations, depending on the add:

One is class-level:

  <classname= "Model.customer, Model"Table= "Customer"Discriminator-value= "0" lazy= "true" >    <!--unsaved-value= "0" does not need to be defined in the primary key table, but it needs to be defined in the child table . -    <IDname= "CustomerId"column= "CustomerId"type= "int"Unsaved-value= "0">      <Generatorclass= "Native" />
。。。。

The other is the collection level.

  <classname= "Model.customer, Model"Table= "Customer"Discriminator-value= "0">..... <Setname= "Orders"Table= "Order" lazy= "true" Generic= "true"Inverse= "true"Cascade= "All">      <Keycolumn= "CustomerId"Foreign-key= "Fk_customerorders"/>       <One-to-manyclass= "Model.order,model"/>    </Set>..... 

Depending on the current test, the deferred load configuration at the collection location overrides the class-level lazy load configuration.

There are two ways to get entities: Get and Load methods. The following combinations were tested:

Class-Level lazy= "true" and class-level lazy= "true" and

Collection-Level lazy= "true" at the collection level lazy= "false"

--------------------------------------------------------------------------

Get Method | Load parent, deferred load child parent non-lazy load

Load Method | Parent-child non- lazy load Parent-child non-lazy loading

From the above you can see:

The load method is to ignore the lazy= "true" configuration, which is always non-lazy loading. When you use the Lode method to obtain a customer, the customer and subset order is always loaded immediately (regardless of where lazy = "true" is configured).

Just and:

Http://blog.knowsky.com/192505.htm

The exact opposite of the description. Who's right and who's wrong, tangled?

Through one night's commissioning:

found that if a breakpoint is set to debug, then load behaves as a non-lazy load, sending an SQL statement,

This could be a problem with the compiler. It says that.

Just and:

Http://blog.knowsky.com/192505.htm

The exact opposite of the description. Who's right and who's wrong, tangled?


should be able to correct it back,

Class-Level lazy= "true" and class-level lazy= "true" and

Collection-Level lazy= "true" at the collection level lazy= "false"

--------------------------------------------------------------------------

Get Method | Load parent, deferred load child parent non-lazy load

Load Method | both father and son delay loading parent-child non-lazy loading

The final conclusion is:

In the case of configuring lazy = "true",

The Get method only delays loading a subset of orders,

The Load method is much better than get, not only delaying loading a subset of orders, but also delaying the loading of the parent customer.

The load method assumes that the parent customer is present and throws an exception if it does not exist "nhibernate.objectnotfoundexception" type of exception,

But this exception, nhibernate own internal processing, and returns an entity class of Proxy (Custmoeproxy), guaranteed not to return a null

As shown in the following:

------------------------------------------

Non-lazy load plots:

Delay Loading plots:

See, when the implementation of delay loading, when orders are required, the session will be queried, session. But at this point, because the session is closed,

So the exception is thrown:

{"initializing[model.customer#336]-failed to lazily initialize a collection of role: Model.Customer.Orders, no session or session was closed"}

To prevent the session from being closed, delay loading fails. The following solutions are available:

 Public Orders lazyloadorders (int  customerId) {    usingnew  SessionManager (). GetSession ())    {        return _session. Get<customer>(customerId). Orders;    }}

This method is called later to get orders

----------------------------------------------------------------------------------------------------------                                                      ----
Ultimate test:


Note: Do not break the point when testing, otherwise it will affect the test results (if you make a breakpoint debugging, you will There is an extra SQL request), the above test is because of the break point to test, the result


the final conclusion of the test, the above results are based on the following test result as the conclusion of the coffin. The <class> and <Set> under

are all settings that are part of the Customer.hbm.xml.

"1" Get method:

<class name = "Customer" lazy= "true" > <class name = "Customer" lazy= "false" >

<set name= "Orders" lazy= "true" > Load customer, do not load orders to load customer, do not load orders

<set name= "Orders" lazy= "false" > Loading customer, loading orders load customer, loading orders


Conclusion: 1. The Get method always loads the customer;
The 2.Get method loads orders and is determined by <set name= "orders" lazy= "" >.



"2" Load Method:

<class name = "Customer" lazy= "true" > <class name = "Customer" lazy= "false" >

<set name= "Orders" lazy= "true" > Both customer and orders do not load the customer and do not load the orders

<set name= "Orders" lazy= "false" > both customer and orders do not load The load customer, load orders

    Conclusion: 1. The Load method will never load the customer and orders as long as the class's lazy is false;
2.Load method as long as the class of the lazy for ture, always load the customer, whether to load oders by <set name= "Orders" lazy= "" > Decision.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.