본문 바로가기

개발/이게 왜 안돼?

[스프링][JPA] Custom Jpa Repository를 추가했는데 에러가 나요

팀원분이 새로운 api를 추가하면서 배포하려는데 빌드 에러가 난다며 에러로그를 공유해 주셨다.

 

Caused by: org.springframework.beans.factory.BeanCreationException: 

Error creating bean with name '{추가한 레파지토리}' defined in 
@EnableJpaRepositories declared on 
JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: 

Invocation of init method failed; nested exception is 
org.springframework.data.repository.query.QueryCreationException

...(생략)

Reason: Method has to have one of the following 
return types[interface org.springframework.data.domain.Slice, 
interface org.springframework.data.domain.Page, interface java.util.List];
nested exception is java.lang.IllegalStateException: 
Method has to have one of the following 
return types[interface org.springframework.data.domain.Slice, 
interface org.springframework.data.domain.Page, interface java.util.List]

새롭게 추가한 custom repository에서 에러가 발생하고 있고 init method 가 실패한다고 한다.

 

기존에 커스텀 레파지토리를 추가한적은 많았지만 이런 에러가 난 적은 처음이어서 원인을 찾는데 한참을 헤맸다.

 

한참 코드를 보다가 문득 이름을 잘못 붙여준게 아닐까 하는 생각이 들었다.

 

기존에는 customRepository 구현체를 선언할때 뒤에 Impl 만 붙여서 동일한 이름을 가지도록 만들어줬는데

인터페이스는 AdminMemberCustomRepository로 되어있고

구현체에는 MemberCustomRepositoryImpl로 선언되어 있었던 것이었다.

 

구현체를 인터페이스와 동일하게 AdminMemberCustomRepositoryImpl로 변경해주고 나니 문제가 해결됐다.

 

Spring Data Jpa 공식문서에 가보니 다음과 같이 note에 적혀있다. (역시 공식문서가 짱이다.)

The most important part of the class name that corresponds to the fragment interface is the Impl postfix.

(출처 : https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-implementations )

 


한 줄 요약

Custom Jpa Repository Impl를 추가할 때는 동일한 이름을 사용해야 한다.
예시. MemberCustomRepository 인 경우 MemberCustomRepositoryImpl 여야 한다.

Spring Data Repository에 대해 좀 더 알아보기 

 

공식문서에 간김에 한번 훑어보면서 정리했다.

기본 crud repository
- memberRepository 

custom repository
- memberCustomRepository (인터페이스)
- memberCustomRepositoryImpl (구현체)