我遇到了将WHERE条件分组的问题。最终,我的目标是拥有一组AND条件,每个条件都是OR。例如:
SELECT *
WHERE ( foo = 1 AND bar = 2)
OR (foo = 3 AND bar = 4)
OR (foo = 5 AND bar = 6)
以下是我用来完成此任务的代码。正如你所看到的,我正在创造2#等于'谓词,然后创建一个嵌套它们的谓词。
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 ) )
简单地颠倒那些和()和或()方法也没有解决我的问题。它导致一切都像是这样:
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 ) )
我尝试过每一个我能想到的组合。任何人都能指出我做错了什么吗?
答案 0 :(得分:2)
尝试改变:
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[] {})));