I have two tables in MySQL database.
- product
- order_item
Customers place orders of products which are stored into the order_item
table - a one-to-many relationship from product
to order_item
.
Currently, I'm executing the following query.
SELECT t0.prod_id,
sum(t1.quantity_ordered)
FROM projectdb.product t0,
projectdb.order_item t1
WHERE (t0.prod_id = t1.prod_id)
GROUP BY t0.prod_id
HAVING (sum(t1.quantity_ordered) >= ?)
ORDER BY sum(t1.quantity_ordered) DESC
Criteria query that produces this SQL is as follows.
CriteriaBuilder criteriaBuilder=entityManager.getCriteriaBuilder();
CriteriaQuery<Object[]>criteriaQuery=criteriaBuilder.createQuery(Object[].class);
Metamodel metamodel = entityManager.getMetamodel();
Root<OrderItem> root = criteriaQuery.from(metamodel.entity(OrderItem.class));
Join<OrderItem, Product> orderItemProdJoin = root.join(OrderItem_.prodId, JoinType.INNER);
List<Expression<?>>expressions=new ArrayList<Expression<?>>();
expressions.add(orderItemProdJoin.get(Product_.prodId));
expressions.add(criteriaBuilder.sum(root.get(OrderItem_.quantityOrdered)));
criteriaQuery.multiselect(expressions.toArray(new Expression[0]));
criteriaQuery.groupBy(orderItemProdJoin.get(Product_.prodId));
criteriaQuery.having(criteriaBuilder.greaterThanOrEqualTo(criteriaBuilder.sum(root.get(OrderItem_.quantityOrdered)), criteriaBuilder.literal(5)));
criteriaQuery.orderBy(criteriaBuilder.desc(criteriaBuilder.sum(root.get(OrderItem_.quantityOrdered))));
List<Object[]> list = entityManager.createQuery(criteriaQuery).getResultList();
This query sums up quantities of each group of products in the order_item
table.
It displays a list of rows that looks like the following.
prod_id qunatity_ordered
6 11
8 8
26 8
7 7
31 7
12 6
27 6
24 5
9 5
Is it possible to just count the number rows which are produced by this query - 9 in this case?
I'm on JPA 2.1 provided by EclipseLink 2.5.2 and Hibernate 4.3.6 final.