Lazy & lt; T & gt; is used to achieve delayed loading of customer orders and lazy orders

Source: Internet
Author: User

Lazy <T> is used to achieve delayed loading of customer orders and lazy orders

"Delayed loading" means loading data as needed. For example, if a Customer information is obtained, the Orders information of the Customer will not be loaded and loaded when the Orders information needs to be displayed. Simply put, it is to load on demand. The advantage of "delayed loading" is to reduce application response time, reduce memory consumption, and avoid unnecessary database interaction.

 

□Instant Loading

Create an Order class and a Customer class. The Customer maintains a set of orders and assigns values to the Order set in the Customer constructor. That is, as long as a Customer instance is created, all orders of the Customer will be loaded.

 

About the Customer and Order classes.

    public class Customer
    {
        private List<Order> _orders = null;
        public List<Order> Orders
        {
            get { return _orders; }
        }
        private string _customerName;
        public string CustomerName
        {
            get { return _customerName; }
            set { CustomerName = value; }
        }
        public Customer()
        {
            _customerName = "darren";
            _orders = LoadOrders();
        }
        private List<Order> LoadOrders()
        {
            List<Order> result = new List<Order>();
            Order o = new Order();
            o.OrderNumber = "001";
            result.Add(o);
            o = new Order();
            o.OrderNumber = "002";
            result.Add(o);
            return result;
        }
    }
    public class Order
    {
        private string _orderNumber;
        public string OrderNumber
        {
            get { return _orderNumber; }
            set { _orderNumber = value; }
        }
    }

 

Client call:

    class Program
    {
        static void Main(string[] args)
        {
            Customer customer = new Customer();
            Console.WriteLine(customer.CustomerName);
            foreach (var order in customer.Orders)
            {
                Console.WriteLine(order.OrderNumber);
            }
            Console.ReadKey();
        }
    }

Place the breakpoint in the row where the foreach is located and add monitoring for the customer variable. It is found that all orders of the Customer are loaded when the Customer instance is created.

 

□Lazy <T> implement delayed Loading

For delayed loading, the requirement here is: Do not load any Order of the Customer when creating the Customer instance, when Orders is traversed and displayed, all Orders of the Customer are loaded.

 

Set the _ orders field of Customer to verify loading.

private Lazy<List<Order>> _orders = null;

 

Modify the get accessors in the Orders attribute of Customer as follows.

        public List<Order> Orders
        {
            get { return _orders.Value; }
        }

 

Modify the constructor as follows:

        public Customer()
        {
            _customerName = "darren";
            _orders = new Lazy<List<Order>>(() => LoadOrders());
        }

 

Customer class, after modification, complete as follows:

    public class Customer
    {
        private Lazy<List<Order>> _orders = null;
        public List<Order> Orders
        {
            get { return _orders.Value; }
        }
        private string _customerName;
        public string CustomerName
        {
            get { return _customerName; }
            set { CustomerName = value; }
        }
        public Customer()
        {
            _customerName = "darren";
            _orders = new Lazy<List<Order>>(() => LoadOrders());
        }
        private List<Order> LoadOrders()
        {
            List<Order> result = new List<Order>();
            Order o = new Order();
            o.OrderNumber = "001";
            result.Add(o);
            o = new Order();
            o.OrderNumber = "002";
            result.Add(o);
            return result;
        }
    }        

Or hit the breakpoint in the client foreach code line to run.


It can be seen that before the traversal, the Value Attribute Value of the _ orders field of Customer is null.

 

F11: Go to loop Traversal

It can be seen that when the traversal is performed to obtain the Order value of the Customer instance, the delay loading starts, and the attribute value of the _ orders field is no longer null.

 

Conclusion: when we want to implement delayed loading for a certain attribute of the class, we first design a Lazy <T> type field, and then in the get accesser of this attribute, use the Value Attribute of the Lazy <T> type field to obtain the Value. Finally, initialize the Lazy <T> type field in the class constructor.


Lazy delayed loading of hibernate in JAVA

Lazy = "true"
It indicates that the child table data is not loaded at the beginning.
It will not load the data of the sub-table until you request the data of the sub-table.

Otherwise, as long as your statement is created, it will retrieve all the data, regardless of the time of the statement.
Maybe the field you want is not the data in the sub-table, but it already has word table data in the buffer.

References:
The delayed loading mechanism is proposed to avoid unnecessary performance overhead. The so-called delayed loading means that data loading is performed only when data is actually needed. Hibernate provides delayed loading of object objects and delayed loading of collections, and delayed loading of attributes in Hibernate3. Next we will introduce the details of these types of delayed loading. A. Delayed loading of Object: To use delayed loading of object, you must configure the ing configuration file of the object as follows:
<Hibernate-mapping> <class name = "com. neusoft. entity. User" table = "user" lazy = "true"> ...... </Class> You can enable the delayed loading feature of an object by setting the lazy attribute of the class to true. If we run the following code: User user = (User) session. load (User. class, "1"); (1) System. out. println (user. getName (); (2) when running at (1), Hibernate does not initiate data query, if we use some debugging tools (such as JBuilder2005's Debug tool) and observe the memory snapshot of the user object at this time, we will be surprised to find that, in this case, the returned object may be of the User $ EnhancerByCGLIB $ bede8986 type and its attribute is null. What is the problem? I still remember that the session. load () method previously mentioned will return the proxy class Object of the object. Here, the returned object type is the proxy class Object of the User object. In Hibernate, CGLIB is used to dynamically construct the proxy class object of a target object, and the proxy class object contains all the attributes and methods of the target object, all attributes are assigned null values. Whether the values get attribute is null. If it is not null, The getName method of the target object is called. If it is null, a database query is initiated to generate an SQL statement similar to this: select * from user where id+'1' then to query data, construct the target object, and assign the value to the cglib?calback_0.tar get attribute. In this way, through an intermediate proxy object, Hibernate achieves object loading delay. Only when a user initiates an action to obtain object attributes can the user initiate a database query operation. Therefore, the delayed loading of objects is completed through the intermediate proxy class, so only session is available. the load () method uses the object to delay loading, because only the session. the load () method returns the proxy class Object of the object class.

Can I dynamically specify the lazy policy for delayed loading of hibernate?

No.
Solution for session Closure of associated Entity

A. Hibernate. initialize (proxy); forcibly load the associated object, such as Hibernate. initialize (user. address );
B. set lazy = "false"
C. Use the fetch of HQL, such as from User fetch all properties
References: if you have other questions, send me a Baidu message.
 

Related Article

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.