title: JPA calculating ranking from ordered selection
body: <p>Say, I have following table.</p>
  
  <pre><code>USER_POINT
    USER_ID    | BIGINT | PK
    USER_POINT | BIGINT |
  </code></pre>
  
  <p>'USER_POINT' may be constantly updated.<br/>
  With given <code>USER_ID</code> I want the number of distance from the top in the selection ordered by <code>USER_POINT</code>.</p>
  
  <pre><code>SEQ    USER_ID  USER_POINT
  -----  -------  -----------
  00001  232132   32423423432
  00002  023944   32423423431
  .....  ......   ...........
  01007  000034   xxxxxxxxxxx // I want to know the 01007 with given 000034
  </code></pre>
  
  <p>I'm not programmed yet but here comes some psuedocode I'm going to try.</p>
  
  <pre class="lang-java prettyprint-override"><code>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;
  }
  </code></pre>
  
  <p>I want to ask</p>
  
  <pre><code>Is this the right way?
  Is this the only way?
  </code></pre>
  
  <p>Thank you.</p>