添加自定义Repository方法后Spring Boot应用启动失败求助
问题描述
我的Spring Boot应用在Repository接口未包含任何自定义方法时运行正常,但一旦添加自定义方法,就会抛出异常导致启动失败。
相关代码
package com.library.repo; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import com.library.entity.ShowEntity; @Repository public interface ShowRepository extends JpaRepository<ShowEntity, Integer> { @Query("SELECT s FROM show_entity s WHERE s.movie.movie_id = :movieId") List<ShowEntity> findShowsByMovieId(int movieId); }
控制台错误信息
Error creating bean with name 'showController' defined in file [/Users/PR20372898/Documents/workspace-spring-tool-suite-4-4.15.1.RELEASE/XYZCinemas/target/classes/com/library/controller/ShowController.class]: Unsatisfied dependency expressed through constructor parameter 0: Error creating bean with name 'showService' defined in file [/Users/PR20372898/Documents/workspace-spring-tool-suite-4-4.15.1.RELEASE/XYZCinemas/target/classes/com/library/service/ShowService.class]: Unsatisfied dependency expressed through constructor parameter 0: Error creating bean with name 'showRepository' defined in com.library.repo.ShowRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Could not create query for public abstract java.util.List com.library.repo.ShowRepository.findShowsByMovieId(int); Reason: Validation failed for query for method public abstract java.util.List com.library.repo.ShowRepository.findShowsByMovieId(int)
问题原因及解决办法
核心原因
自定义JPQL查询存在两处错误:
- JPQL语法要求使用实体类名称而非数据库表名,你写的
show_entity是数据库表名,应该替换为实体类名ShowEntity(除非你在ShowEntity类上通过@Entity(name = "xxx")指定了别名)。 - JPQL引用属性时要使用Java实体类的属性名而非数据库字段名,
s.movie.movie_id中的movie_id是数据库字段名,需要改成MovieEntity类中对应的Java属性名(比如movieId)。
修正后的代码
@Repository public interface ShowRepository extends JpaRepository<ShowEntity, Integer> { @Query("SELECT s FROM ShowEntity s WHERE s.movie.movieId = :movieId") List<ShowEntity> findShowsByMovieId(int movieId); }
更简便的替代方案
Spring Data JPA支持方法名自动推导查询,无需写自定义JPQL,直接用规范的方法名即可生成对应的SQL:
@Repository public interface ShowRepository extends JpaRepository<ShowEntity, Integer> { List<ShowEntity> findByMovieMovieId(int movieId); }
内容的提问来源于stack exchange,提问作者Prajal Saxena
相关产品推荐
相关产品推荐

