AND/OR 在 Hibernate 中使用 Criteria Predicates 对 WHERE 条件进行分组

AND/OR grouping WHERE conditions with Criteria Predicates in Hibernate

我在对 WHERE 条件进行分组时遇到问题。最终,我的目标是拥有一组 AND 条件,每个条件都是一个 OR。例如:

SELECT *
WHERE ( foo = 1 AND bar = 2) 
OR (foo = 3 AND bar = 4)
OR (foo = 5 AND bar = 6)

下面是我用来完成此操作的代码。如您所见,我正在创建 2 'equal' 个谓词,然后创建一个嵌套它们的谓词。

List<Waybill> getWaybillsByCriteriaOrderItemList(List< OrderItem > orderItems ) {
    CriteriaBuilder cb = em.getCriteriaBuilder()
    CriteriaQuery<Waybill> q = cb.createQuery( Waybill )
    Root<Waybill> waybillRoot = q.from(Waybill)
    q.select( waybillRoot )
    List<Predicate> predicates = []


    orderItems.each { OrderItem item ->
        Predicate carInit = cb.equal( cb.trim(waybillRoot.get('carInit')), item.carInit)
        Predicate carNumb = cb.equal( cb.trim(waybillRoot.get('carNumb')), item.carNum )
        Predicate thisCar = cb.or (
                cb.and( carInit ),
                cb.and( carNumb )
        )
        predicates << thisCar
    }
    q.where(predicates.toArray(new Predicate[predicates.size()]))
    TypedQuery<Waybill> tq = em.createQuery(q)
    List<Waybill> result = tq.getResultList()
    result
}

不幸的是,AND/OR 分组与我的预期完全相反。这是生成的 HQL

select generatedAlias0 from Waybill as generatedAlias0 where 
( ( trim(BOTH   from generatedAlias0.carInit)=:param0 ) or ( trim(BOTH   from generatedAlias0.carNumb)=:param1 ) ) 
and 
( ( trim(BOTH   from generatedAlias0.carInit)=:param2 ) or ( trim(BOTH   from generatedAlias0.carNumb)=:param3 ) ) 
and
( ( trim(BOTH   from generatedAlias0.carInit)=:param4 ) or ( trim(BOTH   from generatedAlias0.carNumb)=:param5 ) ) 

简单地反转那些 and() 和 or() 方法也没有解决我的问题。它导致一切都像这样:

 Predicate thisCar = cb.and (
     cb.or( carInit ),
     cb.or( carNumb )
 )

~~~~

select generatedAlias0 from Waybill as generatedAlias0 where 
( ( trim(BOTH   from generatedAlias0.carInit)=:param0 ) and ( trim(BOTH   from generatedAlias0.carNumb)=:param1 ) )
and
( ( trim(BOTH   from generatedAlias0.carInit)=:param2 ) and ( trim(BOTH   from generatedAlias0.carNumb)=:param3 ) )
and
( ( trim(BOTH   from generatedAlias0.carInit)=:param4 ) and ( trim(BOTH   from generatedAlias0.carNumb)=:param5 ) )

能想到的组合我都试过了。谁能指出我做错了什么?

尝试改变:

Predicate thisCar = cb.or (
            cb.and( carInit ),
            cb.and( carNumb )
    );

至:

Predicate thisCar = cb.and( carInit , carNumb );

并在循环之后,将 or 语句添加到谓词数组中:

q.where(cb.or(predicates.toArray(new Predicate[] {})));