【问题标题】:Spring Data JPA on multiple columns with AND clause and combining with OR clause带有 AND 子句并与 OR 子句结合的多个列上的 Spring Data JPA
【发布时间】:2020-01-16 04:01:30
【问题描述】:

我有一个表结构如下

BrandMerchant(id,brand_id,category_id,merchant_id)

我们的请求中有一个列表,我想创建一个查询:

Select * 
from BrandMerchant 
where (brand_id=1 and merchant_id=2 and category_id=3) 
   OR (brand_id=4 and merchant_id=5 and category_id=6) 
   OR (brand_id=5 and merchant_id=4 and category_id=6)` 

...更多取决于列表大小。

我想要一个类似于findByBrandIdAndMerchantIdAndCategoryId 的集合(List<BrandMerchant>)

如何使用spring data jpa或者在java中生成自定义查询来实现上述语句

【问题讨论】:

  • @Query 注释和 gogogogogog.
  • 我同意@Antoniossss 但你也可以使用规范。在这里你可以找到更多here

标签: mysql hibernate spring-data-jpa querydsl predicate


【解决方案1】:

这可以通过FluentJPA 完成。假设:

  • 列表包含品牌、商家和类别 ID 的元组
  • BrandMerchant 定义了相应的访问属性
public List<BrandMerchant> findMerchants(List<Integer[]> params) {

    Function1<BrandMerchant, Boolean> dynamicFilter = buildOr(params);

    FluentQuery query = FluentJPA.SQL((BrandMerchant m) -> {
        SELECT(m);
        FROM(m);
        WHERE(dynamicFilter.apply(m));
    });
    return query.createQuery(em, BrandMerchant.class).getResultList();
}

private Function1<BrandMerchant, Boolean> buildOr(List<Integer[]> params) {
    Function1<BrandMerchant, Boolean> criteria = Function1.FALSE();

    for (Integer[] tuple : params) {
        int brandId = tuple[0];
        int merchantId = tuple[1];
        int categoryId = tuple[2];
        criteria = criteria.or(m -> m.getBrand().getId() == brandId &&
                                    m.getMerchant().getId() == merchantId &&
                                    m.getCategory().getId() == categoryId);
    }

    return criteria;
}

产生以下 SQL:

SELECT t0.* 
FROM t0 
WHERE (((t0.brand = 1) AND ((t0.merchant = 2) AND (t0.category = 3))) OR
 ((t0.brand = 4) AND ((t0.merchant = 5) AND (t0.category = 6))))

有关Dynamic QueriesJPA Respositories integration 的更多详细信息。

【讨论】:

    猜你喜欢
    • 2016-11-15
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    • 2015-08-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    相关资源
    最近更新 更多