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);