Home > other >  Criteria JPA - need to show the variables values from: Object Inside Object Inside Object
Criteria JPA - need to show the variables values from: Object Inside Object Inside Object

Time:08-10

i'm using Criteria Jpa in my Springboot application. I can successfully join 2 entities and both of them brings me the results, but I can't see what is inside the third hierarchical object.

Exemple: I have an object called Product. Inside the Product I have a list of ProductItem. Inside the productItem I have a list of Status.

but when I find for a list of the PRODUCTs (1th object), I recieve an empty list of status(3th) inside the productItem objects.

Criteria class:

        var criteriaBuilder = entityManager.getCriteriaBuilder();
        var criteriaQuery = criteriaBuilder.createQuery(Product.class);
        var rootContractedProduct = criteriaQuery.from(Product.class);

 rootContractedProduct.fetch("status", JoinType.LEFT);
 rootContractedProduct.fetch("productItem", JoinType.LEFT);

TypedQuery<Product> typedQuery = entityManager.createQuery(criteriaQuery);

The entities classes are correctly mapped. I can retrive the STATUS from ProductItem if I do a direct repository search. I think im missing something inside the Criteria class to populate the Status inside ProductItem class.

CodePudding user response:

If i understand your scenario, then your entities looks like following

Product.java

public class Product {
    // ...    
    List<ProductItem> productItem;

    //...
}

ProductItem.java

public class ProductItem {
    
    //...
    Status status;

    //...
}

Status.java

public class Status {
    //...
}

To fetch the products with list of productItem inside it having the status object consider the following

root = ...
query = ...

Fetch<Product, ProductItem> productItemFetch = root.fetch("productItem", JoinType.LEFT);
productItemFetch.fetch("status", JoinType.LEFT);

This way you can fetch upto 3rd level objects.

  • Related