Confusion over lazy load


#1

I am following a course on Spring / Hibernate and the instructor keeps insisting that a lazy load occurs when you get the data using the getWhatever method (in this case, the getCourses() method). From the behaviour I have seen, the load seems to actually happen when the data is used, not when it is requested.

Viewing the snippet which aims to show a way to get around lazy loading and having a session closed, the exception for accessing data through a closed session still happens.

    public static void main(String[] args) {
        // Create session factory
        SessionFactory factory = new Configuration()
                                    .configure("hibernate.cfg.xml")
                                    .addAnnotatedClass(Instructor.class)
                                    .addAnnotatedClass(InstructorDetail.class)
                                    .addAnnotatedClass(Course.class)
                                    .buildSessionFactory();
        
        // create session
        Session session = factory.getCurrentSession();
        
        try {
            
            // Begin the transaction
            System.out.println("Starting transaction");
            session.beginTransaction();
            
            Instructor instructor = session.get(Instructor.class, 1);
            System.out.println("App: Instructor: " + instructor);
            InstructorDetail id = instructor.getInstructorDetail();
            System.out.println("App: Details: " + id);

            // EXCEPTION SHOULD OCCUR ON THE FOLLOWING LINE
            List<Course> courses = instructor.getCourses();
            
            // Commit
            System.out.println("Committing");
            session.getTransaction().commit();
            session.close();
            
            //  EXCEPTION ACTUALLY HAPPENS HERE
            System.out.println("App: Courses: " + courses);

I’ve run it under debug, and I think I’m right as the hibernate code isn’t touched until the system.out.println() at the end of my snippet. To my mind, that would make it very lazy loading indeed.

Am I going mad, or is that what’s happening?

Loving the ORM and the validation by the way. Thank you to dev team.


#2

If the courses collection is marked with FetchType.LAZY, then it will be a lazy association and, this example:

//  EXCEPTION ACTUALLY HAPPENS HERE
System.out.println("App: Courses: " + courses);

should be changed to:

//  EXCEPTION ACTUALLY HAPPENS HERE
System.out.println("App: Courses: " + courses.size());

By calling the size collection method, you will force Hibernate to initialize the collection. But since the Session is closed, the LazyInitializationException will be thrown.