Hibernate lazy loading

Hibernate uses a proxy object to support lazy loading. Basically as soon as you reference a child or lookup object via the accessor/getter methods, if the linked entity is not in the session cache (i.e. the first-level cache), then the proxy code will go off to the database and load the linked object. It uses javassist (or CGLIB ) to effectively and dynamically generate sub-classed implementations of your objects.

Let’s look at an example. An employee hierarchy table can be represented in a database table as shown below

1
2
3
4
5
6
7
8
9
10
11
public class Employee {
   private Long id;
   private String name;
   private String title;
   private Employee superior;
   private Set<Employee> subordinates;
   //getters and setters are omitted
}

In the above example, if you use lazy loading then the “superior” and “subordinates” will be proxied (i.e. not the actual object, but the stub object that knows how to load the actual object) when the main “Employee” object is loaded. So, if you need to get the “subordinates” or “superior” object, you invoke the getter method on the employee likeemployee.getSuperior( ) and the actual object will be loaded.

 

FROM HERE

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s