'Unidirectional ManyToMany JPA Specification

I have the following entities StockItem, Product and ProductCategory.

  • StockItem ManyToOne with Product
  • Product Unidirectional ManyToMany with ProductCategory

Product class has no reference of ProductCategory, but ProductCategory has collection of Product

I wanted to use JPS specification to query StockItems for a given ProductCategory

Class outlines are as below.

STOCK ITEM class looks like

@Entity    
public class StockItem {
 ...
   @ManyToOne
   private Product product;
 ...

}

PRODUCT class skeleton

@Entity    
public class Product {
 ...
   private String productName;
 ...

}

PRODUCT CATEGORY is as follows

@Entity    
public class ProductCategory {
 ...

   @NotNull
   private String categoryName;

   @ManyToMany
   @NotNull
   private Set<Product> products = new HashSet<>();
 ...

}

I wanted to query SaleLineItems based on productCategoryId. I made an attempt but am stuck with the following code.

    public List<SaleLineItem> findAllByProductCategory(LongFilter productCategoryFilter,
            Specification<SaleLineItem> specification) {
        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<SaleLineItem> cq = cb.createQuery(SaleLineItem.class);
        Root<ProductCategory> productCategoryRoot = cq.from(ProductCategory.class);
        ListJoin<ProductCategory, Product> lj = productCategoryRoot.joinList(ProductCategory_.PRODUCTS);
        
        Root<StockItem> stockItemRoot = cq.from(StockItem.class);
        Join<StockItem, Product> kl = stockItemRoot.join(StockItem_.product);

        // How to combine lj and kl :)

        return null;
    }

ERD Diagram

What would be the way to achieve this?



Solution 1:[1]

cb.equals(lj.get(Product_.id), kl.get(Product_.id)

Will give you the predicate you need to link your tables which you can return as the predicate for your method to use.

Alternatively, you can use it to define the join statement on lt using:

lj.on(cb.equals(lj.get(Product_.id), kl.get(Product_.id));

but I don't know how Spring handles the query if you return null.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chris