Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Hibernate @OneToMany FetchType.LAZY is not working

I have a product class and the list of Required stock of products
I am having problems while fetching products from database

@Entity
public class Product {

@OneToMany(mappedBy =  "product",cascade = CascadeType.REMOVE, fetch = FetchType.LAZY)
    private List<RequiredStock> requiredStocks;

}

Once I call the findAll method from the product repository RequiredStock are fetched eagerly

public List<Product> getAllProducts(){
        return productRepository.findAll();
    }

this is the response I got from postman

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
    {
        "id": 26,
        "requiredStocks": [
            {
                "id": 54,
                "amount": 5.0,
                "stock": {
                    "id": 1,
                    "stockName": "Sugar",
                    "quantity": 500.0,
                    "stockUnit": "GRAM",
                    "unitPrice": 25.0
                }
            }
        ],
    },
    {
        "id": 28,
        "requiredStocks": [
            {
                "id": 55,
                "amount": 2.0,
                "stock": {
                    "id": 1,
                    "stockName": "Sugar",
                    "quantity": 500.0,
                    "stockUnit": "GRAM",
                    "unitPrice": 25.0
                }
            }
        ],
       
    },
...

I do not want to fetch RequiredStocks from the api

>Solution :

I think the problem here is miss-understanding of how LAZY relations work. When a relation is marked as LAZY it is not retrieved when the along the main object (in this case Product) but when the property is accessed (when you invoke getRequiredStock.

So, I guess you are mapping the Product to a dto or returning Products from you API, which causes the getter to be invoked and triggers the relation query.

In this case I would recommend avoid mapping requiredStock property or ignore that property using a custom dto class without requiredStock.

Here is a more in detail SO Question about the differences of EAGER and LAZY: Difference between FetchType LAZY and EAGER in Java Persistence API?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading