Jin Kwon
Jin Kwon

Reputation: 22017

JPA calculating ranking from ordered selection

Say, I have following table.

USER_POINT
  USER_ID    | BIGINT | PK
  USER_POINT | BIGINT |

'USER_POINT' may be constantly updated.
With given USER_ID I want the number of distance from the top in the selection ordered by USER_POINT.

SEQ    USER_ID  USER_POINT
-----  -------  -----------
00001  232132   32423423432
00002  023944   32423423431
.....  ......   ...........
01007  000034   xxxxxxxxxxx // I want to know the 01007 with given 000034

I'm not programmed yet but here comes some psuedocode I'm going to try.

public int getRank(final Long userId) {
    final int pageSize = 500;
    int pageCount = 0;
    int firstResult = 0;
    for (int firstResult = 0; true; firstResult += pageSize) {
        final Query query = em.createQuery(
            "SELECT u.id FROM UserPoint u ORDER BY u.point");
        query.setFirstResult(firstResult);
        query.setMaxResults(pageSize);
        final List orders = query.getResultList();
        if (orders.isEmpty()) {
            break;
        }
        final int index = orders.indexOf(userId);
        if (index != -1) {
            return pageSize * pageCount + index;
        }
        pageCount++;
    }
    return -1;
}

I want to ask

Is this the right way?
Is this the only way?

Thank you.

Upvotes: 0

Views: 5946

Answers (1)

JB Nizet
JB Nizet

Reputation: 692073

JPQL doesn't support such queries. You should use SQL for such queries if you want to make them efficient.

In Oracle, such a query would look like

select r from (select user_id, user_point, rownum as r 
               from user_point 
               order by user_point desc) where user_id = 34

Upvotes: 1

Related Questions