DEV Community

Cover image for Hibernate - LAZY fetching
Yiğit Erkal
Yiğit Erkal

Posted on • Updated on

Hibernate - LAZY fetching

I know what is LAZY in theoretically. Tell me in a real world scenario!!!

Consider an online store, which is a standard Internet web application. A product catalog is kept at the store. This may be depicted as a catalog entity handling a collection of product entities at the most basic level. There might be tens of thousands of goods divided into many overlapping categories in a large store.
The catalog must be loaded from the database when a consumer enters the store. We presumably don't want the implementation to load each and every one of the entities that represent the tens of thousands of goods into memory. Given the amount of physical memory available on the system, this may not even be practical for a sufficiently big store.
Even if this were possible, the site's performance would almost certainly suffer as a result. Instead, we'd like the catalog to load first, followed by the categories. Only a fraction of the goods in each category should be loaded from the database when the user digs down into the categories.
Hibernate includes a feature called lazy loading to address this issue. When enabled, the associated entities of an entity will only be loaded when they are specifically requested.

How can 'LAZY' solve the above problem? 🐌

Look at the below manner:

//Following code loads only a single category from the database
Category category = (Category)session.get(Category.class,33);

//This code will fetch all products for category 33 from database
Set<Product> products = category.getProducts();
Enter fullscreen mode Exit fullscreen mode

This solves the problem right? Now, Hibernate will make it for you... Look at the below code snippet:

@OneToMany( mappedBy = "category", fetch = FetchType.LAZY )
private Set<ProductEntity> products; 
Enter fullscreen mode Exit fullscreen mode

To sum up

Advantages:

  • Much smaller initial load time than in the other approach
  • Less memory consumption than in the other approach

Disadvantages:

  • Delayed initialization might impact performance during unwanted moments.
  • In some cases we need to handle lazily initialized objects with special care, or we might end up with an exception. (which will be mentioned in the next post)

Top comments (0)