J
J
Jake Taylor2021-11-13 19:09:33
Hibernate
Jake Taylor, 2021-11-13 19:09:33

How to compose a query using JPQL?

There is a SQL query:

SELECT user_id, sum_price FROM (
    SELECT user_id, sum_price, RANK() OVER (order by sum_price DESC) AS r
    FROM (SELECT user_id, SUM(price) sum_price FROM `order` GROUP BY user_id) t
) AS t2
WHERE r = 1;


I'm trying to compose this query using JPQL, but it doesn't work:
CriteriaQuery<UserPrice> cq = cb.createQuery(UserPrice.class);
        Root<Order> from = cq.from(Order.class);

        Subquery<Order> sQuery = cq.subquery(Order.class);

        Root<Order> sFrom = sQuery.from(Order.class);
        Path<User> sUser = sFrom.get(ParameterName.USER);
        Path<BigDecimal> sPrice = sFrom.get(ParameterName.PRICE);

        Expression<BigDecimal> sSum = cb.sum(sPrice);
        Predicate restriction = cb.equal(sQuery, NumberUtils.INTEGER_ONE);

        cq.multiselect(sUser, sSum)
                .orderBy(cb.desc(sSum))
                .groupBy(sUser)
                .where(restriction);


How to compose this query using JPQL?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question