简体   繁体   中英

Customize JPA CriteriaQuery's on-clause

Is there a way to further restrict a join by adding some expressions? With plain sql i write:

SELECT c.*, COUNT(i.id) invoice_count
FROM customers c
LEFT JOIN invoices i ON i.customer_id = c.id
    AND i.creation_time >= '2012-01-01' -- <= extra restriction
    AND i.creation_time < '2013-01-01' -- <= extra restriction
GROUP BY c.id

I haven't found a way to implement this with JPA 2.0 CriteriaQuery.

Update: As requested my (simplified) code so far (without the extra restriction):

CriteriaQuery<CustomerAndInvoiceCount> criteriaQuery = criteriaBuilder.createQuery(CustomerAndInvoiceCount.class);

Root<Customer> customer = criteriaQuery.from(Customer.class);
ListJoin<Customer, Invoice> invoices = customer.join(Customer_.invoices, JoinType.LEFT);

criteriaQuery.select(criteriaBuilder.construct(
        CustomerAndInvoiceCount.class,
        customer,
        criteriaBuilder.count(invoices)));
criteriaQuery.groupBy(customer);

您应该只能够添加条件谓词,而不必担心它们是否属于ON子句或WHERE子句。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM