JPARepository 상속받은 후 OrderBy 관련 쿼리 메소드 추가시 발생하는 오류
상황
Spring Boot 프로젝트에서 Repository 구현시 JPARepository를 상속(extends)하고 별도의 쿼리 메소드를 구현할 때 발생한 오류입니다.
안내되는 오류 메세지를 텍스트로 써보자면 아래와 같습니다.
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'adminUserPasswordRepository' defined in com.logsjejustone.webapiserver.user.repository.AdminUserPasswordRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Could not create query for public abstract com.logsjejustone.webapiserver.user.domain.AdminUserPassword com.logsjejustone.webapiserver.user.repository.AdminUserPasswordRepository.findFirstOrderByNoDesc(); Reason: Failed to create query for method public abstract com.logsjejustone.webapiserver.user.domain.AdminUserPassword com.logsjejustone.webapiserver.user.repository.AdminUserPasswordRepository.findFirstOrderByNoDesc(); No property 'desc' found for type 'Integer' Traversed path: AdminUserPassword.no. |
주요한 오류 메세지만 추출하자면, 아래와 같습니다.
No property {Order By 종류} found for type {Order By 적용할 컬럼 타입} Traversed path: {Order By 적용할 컬럼}
오류 발생할 때 당시 사용한 코드는 아래와 같습니다.
public interface AdminUserPasswordRepository extends JpaRepository<AdminUserPassword, AdminUserPasswordKey> {
AdminUserPassword findFirstOrderByNoDesc();
...
}
원인
구글링을 계속하다보니 Ordering not workiing [DATAJPA-814] 로 본 이슈가 해결된 이력을 확인하였으며, 이를 요약하면 아래와 같습니다.
The first By in a query method indicates the start of a path expression.
첫 'By'는 Path 시작 위치를 지정한다고 하여 OrderBy의 By가 시작 위치 지시자로 인식되어 오류가 발생하는 문제였습니다.
해결 방법
find 뒤 Get할 데이터의 갯수를 지정하는 키워드(First, All, Top, First3, 등)와 OrderBy 사이에 'By'를 한번 더 입력합니다.
즉, 아래 코드 중에서 좌측의 코드가 아닌 우측의 코드 방식으로 작성하니 오류가 해결되었습니다.
- findFirstOrderByIdDesc() → findFirstByOrderByIdDesc()
- findTop3OrderByNoDesc() → findTop3ByOrderByNoDesc()
- findAllOrderByIdAsc() → findAllByOrderByIdAsc()
변경된 코드
public interface AdminUserPasswordRepository extends JpaRepository<AdminUserPassword, AdminUserPasswordKey> {
AdminUserPassword findFirstByOrderByNoDesc();
...
}
References
- https://stackoverflow.com/questions/19733464/order-by-date-asc-with-spring-data
- https://github.com/spring-projects/spring-data-jpa/issues/1174
댓글