2012-03-13 2 views
0

말, 다음 표가 있습니다.JPA 순위 선택에서 순위 계산

USER_POINT 
    USER_ID | BIGINT | PK 
    USER_POINT | BIGINT | 

'USER_POINT'이 (가) 지속적으로 업데이트 될 수 있습니다.
주어진 USER_ID을 사용하면 선택에서 위로부터 거리의 수를 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 

저는 아직 프로그래밍되지 않았지만 여기에 몇 가지 코드가 있습니다. 시도해 보겠습니다.

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

나는

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

감사합니다 물어보고 싶은.

답변

1

JPQL은 이러한 쿼리를 지원하지 않습니다. 이러한 쿼리를 효율적으로 사용하려면 SQL을 사용해야합니다.

오라클, 이러한 쿼리는 JPA는`query` 자체를 지원하지 않는 그것이 사실

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

과 같을 것이다? 아니면 JDBC를 사용하는 것이 좋습니다? –

+0

JPQL에서 그런 쿼리를 작성할 수 없습니다. 네이티브 SQL 쿼리를 사용하십시오. 그러나 원시 SQL 쿼리를 실행하기 위해 JDBC를 사용할 필요는 없습니다. EntityManager에는 createNativeQuery()가 있습니다. –