Search code examples
spring-boothibernatespring-data-jpaone-to-many

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

[
    {
        "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 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?