构建规范(条件 API)

Build specification (Criteria API)

我的实体:

public class Product extends BaseEntity {
    @OneToMany(mappedBy = "product", cascade = CascadeType.ALL)
    List<Price> prices;
}

public class Price extends BaseEntity {

    BigDecimal price;

    @ManyToOne(fetch = FetchType.LAZY)
    Product product;
}

我的搜索条件:

public class ProductSearchCriteria {

    private Optional<BigDecimal> minP;
    private Optional<BigDecimal> maxP;
}

我的规格:

    public static Specification<Product> priceBetween(Optional<BigDecimal> minP, Optional<BigDecimal> maxP) {
    return (root, query, builder) -> {
        //Subquery<Product> sq = query.subquery(Product.class);
        //CriteriaQuery<Price> priceCriteriaQuery = builder.createQuery(Price.class);
        //Root<Price> priceRoot = sq.from(Price.class);

        return minP.map(min -> {
            return maxP.map(max ->
                    //builder
                    ).orElse(null);
        }).orElse(null);
    };
}

在我的规范中,我试图检索价格介于(价格 1、价格 2)之间的产品,但无法建立标准

我试过了(但生成的查询是错误的):

max-> builder.between(root.get(Product_.PRICES), min, max)

我自己使用 Join:

解决了这个问题
 Join<Product, Price> productPriceJoin = root.join(Product_.PRICES, JoinType.LEFT);

max -> builder.between(productPriceJoin.get(Price_.PRICE), min, max))

完整的解决方案如下所示:

public static Specification<Product> priceBetween(Optional<BigDecimal> minP, Optional<BigDecimal> maxP) {
        return (root, query, builder) -> {
            Join<Product, Price> productPriceJoin = root.join(Product_.PRICES, JoinType.LEFT);
            return minP.map(min -> {
                return maxP.map(max ->
                        builder.between(productPriceJoin.get(Price_.PRICE), min, max))
                        .orElse(null);
            }).orElse(null);
        };
    }