Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 14, 2022 03:37 pm GMT

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 databaseCategory category = (Category)session.get(Category.class,33);//This code will fetch all products for category 33 from databaseSet<Product> products = category.getProducts();

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; 

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)

Original Link: https://dev.to/yigi/hibernate-lazy-fetching-aeh

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To