[NHibernate] load now

Source: Internet
Author: User

[NHibernate] load now
Example 1: One-to-multiple relationships load customer information and customer order information by loading them immediately. Copy code 1 // <summary> 2 // load the customer information in the immediate manner 3 // </summary> 4 // <param name = "customerID"> </param> 5 // <returns> </returns> 6 public Customer GetCustomerByImmediatelyLoad (Guid customerID) 7 {8 // get ISession instance 9 // release the session through using. To ensure that the data is loaded immediately, instead of the delayed loading 10 // remember the last article mentioned in the delayed loading, when the session is closed, when reading the data again, there will be an exception. 11 // if you forget it, you can go back to the previous article to view 12 using (ISession session = NHibernateHelper. getSession () 13 {14 r Eturn session. get <Customer> (customerID); 15} 16} copy code 1.1 and modify Customer. hbm. the xml file uses the Lazy method to load data by default, that is, the default Lazy = "true", and the specified Lazy = "false" must be displayed ". 1 <! -- One-to-multiple relationship: a customer can have one or more orders --> 2 <! -- The child entity is responsible for maintaining the association relationship --> 3 <set name = "Orders" table = "TB_Order" generic = "true" inverse = "true" cascade = "all" lazy = "false "> 4 <key column =" CustomerID "foreign-key =" FK_TB_Order_TB_Customer "> </key> 5 <one-to-define class =" Wolfy. shop. domain. entities. order, Wolfy. shop. domain "/> 6 </set> compile a test and verify, and call the using Method in the data access layer to force the resource clearing Session to load the Customer object to load a Customer object, at this time, nhib.pdf immediately loads the Order object associated with the Customer. Use the nhibtil class (NHibernateUtil) to test whether the associated Customer object set has been initialized (that is, loaded ). As described in the previous article, if the session is closed, if you expand the orders attribute of the customer, an exception will occur. This also means that the Orders are loaded immediately like the customer. View the generated SQL statement 1 exec sp_executesql n' SELECT mermer0 _. customerID as CustomerID0_0 _, customer0 _. version as Version0_0 _, customer0 _. customerName as Customer3_0_0 _, customer0 _. customerAddress as Customer4_0_0 _ FROM TB_Customer customer0 _ WHERE customer0 _. customerID = @ p0 ', n' @ p0 uniqueidentifier', @ p0 = 'b0720295-9541-40B3-9994-610066224DB8 '2 3 exec sp_executesql n' SELECT orders0 _. customerID as CustomerID1 _, Orders0 _. orderID as OrderID1 _, orders0 _. orderID as OrderID1_0 _, orders0 _. orderDate as OrderDate1_0 _, orders0 _. customerID as CustomerID1_0 _ FROM TB_Order orders0 _ WHERE orders0 _. customerID = @ p0 ', n' @ p0 uniqueidentifier', @ p0 = 'b0720295-9541-40B3-9994-610066224DB8 'the first SQL statement queries the Customer, the second SQL statement is used to query the order associated with the customer. 1.2. The NHibernateUtil entity class nhibtil provides the entity class (NHibernateUtil) to detect whether the associated object set has been initialized, And to forcibly initialize the uninitialized associated objects. With this function, we can modify the methods in the data access layer, add the NHibernateUtil class to the method of forcibly clearing and closing the Session Using to provide the Initialize method to Initialize the Order object set associated with the Customer. Modify the Customer. hbm. xml file, set the lazy attribute of the set node to the default value true, or delete the property. Copy code 1 // <summary> 2 // NHibernateUtil mode, load customer information and associated data immediately 3 // </summary> 4 // <param name = "customerID"> </param> 5 // <returns> </returns> 6 public Customer GetCustomerByImmediatelyLoadNHibernateUtil (Guid customerID) 7 {8 // get ISession instance 9 // release the session through using. To ensure that the data is loaded immediately, instead of the delayed loading 10 // remember the last article mentioned in the delayed loading, when the session is closed, when reading the data again, there will be an exception 11 // if you forget it, you can go back to the previous article to view 12 using (ISession session = NHiberna TeHelper. getSession () 13 {14 Customer customer Customer = session. get <Customer> (customerID); 15 // 16 // Summary: 17 // Force initialization of a proxy or persistent collection.18 // 19 nhib.pdf. NHibernateUtil. initialize (customer. orders); 20 return customer; 21} 22} by copying the code in this way, as shown in the preceding test results, the texture will no longer be attached. 2. For multi-to-Multi-relationship 2.1, use the Lazy = "false" attribute example as shown in the preceding figure. 2.2. Use the NHibernateUtil sort class to analyze multiple instances using Order and Product. If you want to load all products under the Order, you can use the NHibernateUtil class to initialize the associated objects (get them from the database ). Copy code 1 // <summary> 2 // NHibernateUtil mode, load order and product 3 now /// </summary> 4 /// <param name = "customerID"> </param> 5 /// <returns> </returns> 6 public Order GetOrderProductByImmediatelyLoadNHibernateUtil (Guid orderId) 7 {8 using (var session = NHibernateHelper. getSession () 9 {10 var order = session. get <Wolfy. shop. domain. entities. order> (orderId); 11 // force initialize customer12 nhib.pdf. NHibernateUtil. initializ E (order. customer); 13 // force initialize Product14 nhib.pdf. NHibernateUtil. initialize (order. products); 15 return order; 16} 17} 1 exec sp_executesql N 'select order0 _. orderID as OrderID1_0 _, order0 _. orderDate as OrderDate1_0 _, order0 _. customerID as CustomerID1_0 _ FROM TB_Order order0 _ WHERE order0 _. orderID = @ p0 ', n' @ p0 uniqueidentifier', @ p0 = '78a53f67-A293-48A1-BBE2-86FED77342FA '2 3 exec sp_executesql n' SELECT cu Stomer0 _. customerID as CustomerID0_0 _, customer0 _. version as Version0_0 _, customer0 _. customerName as Customer3_0_0 _, customer0 _. customerAddress as Customer4_0_0 _ FROM TB_Customer customer0 _ WHERE customer0 _. customerID = @ p0 ', n' @ p0 uniqueidentifier', @ p0 = 'b0720295-9541-40B3-9994-610066224DB8 '4 5 exec sp_executesql n' SELECT products0 _. orderID as OrderID1 _, products0 _. productID as ProductID1 _, product1 _. ProductID as ProductID3_0 _, product1 _. name as Name3_0 _, product1 _. price as Price3_0 _ FROM TB_OrderProduct products0 _ left outer join TB_Product product1 _ on products0 _. productID = product1 _. productID WHERE products0 _. orderID = @ p0 ', n' @ p0 uniqueidentifier', @ p0 = '78a53f67-A293-48A1-BBE2-86FED77342FA 'copy the code here three SQL statements are generated to query and Order associated customer and Product. 2.3 The HQL capture policy supports the following connection types: inner join (inner join), left outer join (left outer join), and right outer join (right outer join) full join (full join, not commonly used ). The "fetch capture" connection allows only one selection statement to initialize the associated objects with the initialization of their parent object, this effectively replaces the external join and latency attribute declaration in the ing file. Note: fetch is not shared with setMaxResults () or setFirstResult () because these operations are based on the result set and may contain duplicate data when pre-capturing the set, that is to say, you cannot know the exact number of rows in advance. Fetch cannot be used with an independent with condition. You can create cartesian products by fetch multiple sets in one query. Therefore, pay attention to this. For multi-to-Multi- ing, the join fetch multiple set roles may give unexpected results in some cases. Please be careful. Using full join fetch and right join fetch is meaningless. If you use Attribute-level delayed retrieval, you can use fetch all properties in the first query to force NHibernate to immediately obtain the attributes that originally require delayed loading. Reference: http://www.cnblogs.com/lyj/archive/2008/10/29/1322373.html test code copy code 1 // <summary> 2 // HQL mode, load order and product 3 now /// </summary> 4 /// <param name = "customerID"> </param> 5 /// <returns> </returns> 6 public Order GetOrderProductByImmediatelyLoadHQL (Guid orderId) 7 {8 using (var session = NHibernateHelper. getSession () 9 {10 return session. createQuery ("from Order o" + 11 "left outer join fetch o. produc Ts "+ 12" inner join fetch o. customer where o. orderID =: orderId ") 13. setGuid ("orderId", orderId) 14. uniqueResult <Order> (); 15} 16} described a N + 1 problem in the previous article. Here, I will explain the N + 1 problem again, I understand that you wanted one. However, when loading by default with delayed loading, all the information will be loaded, which is a waste of time. In this case, the method of loading immediately is used, you can control the number of loaded entries. Summary This article introduces the method of immediate loading of nhibernate, when to use immediate loading, and when to use delayed loading, depending on the situation in the project. For example, if you want to load a few pieces of data in a multi-to-many relationship, that is, N + 1, it is better to load the data immediately, it does not load unnecessary data and can achieve better control.

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.