简体   繁体   中英

How do you PRACTICALLY use lazy loading in your application?

I see a lot of places where expert delvelopers advice to LAZY load the persisted entities in order to save memory.

The concept is quite clear: it is useless to load tons of information you're not going to use .

However, in my everyday experience to apply this best practice comes up to be not trivial at all. I mean, if I define a dependency , let's say a one-to-many relation between a DEPARTMENT and an EMPLOYEE , it is very likely I'll need the list of employees while handling the Department in my business logic. This thing is common and I find myself to use EAGER loading in the most of the cases.

From a programmatically point of view, the best I can do is to ship my Dao methods with a flag like that

public Department getDepartment(String departmentName, boolean eagerly)

where the eagerly attribute set to true triggers a full loading of the Department (which is LAZY loaded by default. I call the getEmployees() inside the transaction to load the employees list).

How do you handle the problem? Do you feel confortable with the LAZY loading? If so, am I missing something?

EDIT:

According to the @Ayman explanation I'd like to discuss the following approach, with hibernate.

    public class Node {
        private Node parent;
        private Set<Node> children;

        public getParent(){
            if(parent==null)
                return Hibernate.initialize(parent);
            return parent;
        }

        public getChildren(){
            if(children==null)
                return Hibernate.initialize(children);
            return children;
        }
    }

Is it an acceptable implementation? What are the drawbacks?

It depends on the situation. I do not recommend adding the eagerly flag as it exposes internal working of your library. It should be transparent to the user.

The way I usually do it is in the classes. The department will have a list of employees. When reading the department, just read the dept table and leave the emp array as null. Then when you have to access the employees, see if the list was loaded or not. Should be fairly easy to implement and shields the library user from knowing the internals of the lib.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM