我有两张桌子:
客户有一个OneToMany关联,用于列出发票。
我想使用CriteriaBuilder来创建这个选择:
select
...
from
Client c
where
(select count(1) from Invoice i where i.id = c.invoiceId) > 0
我该怎么做?
答案 0 :(得分:1)
JPQL
可以使用:
Query query = em.createQuery
("SELECT c FROM Client c WHERE (SELECT COUNT(i) FROM Invoice i WHERE i.client= c) > 0");
List<Client> clientc=query.getResultList());
,但Criteria API
使用subquery
,where clause
需要CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Client> q = cb.createQuery(Client.class);
Root<Client> client = q.from(Client.class);
q.select(client);
Subquery<Invoice> sq= q.subquery(Invoice.class);
Root<Invoice> invoice= sq.from(Invoice.class);
sq.select(invoice);
Predicate sqp = cb.equal(client.get("id"), invoice.get("invoiceId"));
sq.where(sqp);
q.where(cb.exists(sq));
,你需要下面的东西(也许这不是你想要的我不确定因为没有测试我只是写下来):
{{1}}