Spring Data JPA のリポジトリで、findAllOrderBy... のメソッドがあるとエラーが発生しました。
これから、エラーを解決する方法を書いていきます。
バージョン
- SpringBoot 3.0.1
- Java 17
1. 対応方法
OrderBy の前に By を付けるとエラーが発生しなくなります。
findAllByOrderBy...
2. 対応方法の具体例
具体的なリポジトリのコードを以下に記載します。
2.1. エラーが発生しないメソッド名
public interface StudentRepository extends CrudRepository<Student, Long> { List<Student> findAllByOrderById(); }
2.2. エラーが発生するメソッド名
public interface StudentRepository extends CrudRepository<Student, Long> { List<Student> findAllOrderById(); }
3. エラー内容
上の「エラーが発生するメソッド名」でアプリを起動すると、以下のエラーメッセージ(クエリが作成できない)が出力されました。
Could not create query for public abstract java.util.List org.example.repository.StudentRepository.findAllOrderById();
スタックトレースは以下の通りです。
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'studentController':
Unsatisfied dependency expressed through field 'repository': Error creating bean with name 'studentRepository' defined
in org.example.repository.StudentRepository defined in @EnableJpaRepositories declared on
JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Could not create query for public abstract java.util.List
org.example.repository.StudentRepository.findAllOrderById(); Reason: Failed to create query for method public abstract java.util.List
org.example.repository.StudentRepository.findAllOrderById(); Method public abstract java.util.List
org.example.repository.StudentRepository.findAllOrderById() expects at least 1 arguments but only found 0;
This leaves an operator of type SIMPLE_PROPERTY for property id unbound
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:712) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:692) ~[spring-beans-6.0.3.jar:6.0.3]
・・・省略・・・
4. WHERE句がある場合
WHERE句がある場合は、OrderBy の前に By を付けないようにします。
findByNameOrderById(String name);
findByNameContainingOrderById(String name);
※ OrderBy の前に By を付けるとエラーになります。