Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA: lazy loading doesn't load even after the getter method is used. May it be?

Can you simply explain me what means the phrase below:

A relationship that is specified or defaulted to be lazily loaded might or might not cause the related object to be loaded when the getter method is used to access the object. The object might be a proxy, so it might take actually invoking a method on it to cause it to be faulted in. (Pro JPA 2: Mastering the Java Persistence API, page 102)

My questions are:

  1. Does it mean that lazy_loaded_object might not be loaded even after the getLazyLoadedObj() method?
  2. If the answer to the first question is 'YES', than what returns from the getLazyLoadedObj() method?
  3. I still don't understand what will change if the lazy_loaded_object is the proxy. Please, explain it to me.

Thank you in advance.

like image 601
VB_ Avatar asked Oct 22 '25 00:10

VB_


1 Answers

To answer 1) Yes. To understand 2) and 3) lets take an example

Lets say that you have a class Parent and it has Child. You define the Child to be loaded lazily.

class Parent {

  Child chil;

  //FetchMode = lazy
  public Child getChild() {
      return child;
  }

}

Lets say, you have loaded Parent instance already using hibernate session, say parent

Now when you call parent.getChild(); the returning object can be an instance of Child or it could be a Proxy.

What is a Proxy?

Proxy are like interceptors to your class, A proxy for Child gets invoked just before any method of the child gets invoked..

For instance, when you invoke child.getName() --> lets say

proxy.someProcessing() method gets invoked which internally invokes the child.getName() and finally returns the data.

Why we need proxy?

The definition of lazy loading is load when its required. So just before child.getName() gets invoked by proxy, proxy.someProcessing() method calls the DB and gets the CHILD (DB Table mapped to Child) 's column data and loads the child object.

like image 97
sanbhat Avatar answered Oct 23 '25 15:10

sanbhat