JPA派生查询报错:自定义findById方法无法创建查询的问题排查
问题:Spring Data JPA派生查询根据ID查询Bird实体报错
相关代码
Bird实体类
@Entity @Data public class Bird { @Id @GeneratedValue(strategy = IDENTITY) private Long id; @Column(unique = true) @NotEmpty(message = "Name must not be null or empty") private String name; @Enumerated(EnumType.STRING) private Sex sex; // other stuff }
BirdRepository
public interface BirdRepository extends JpaRepository<Bird, Long> { Bird findById(Long Id); }
BirdServiceImpl
@Service @Transactional @Slf4j @RequiredArgsConstructor public class BirdServiceImpl implements BirdService { private final BirdRepository birdRepository; @Override public Bird get(Long id) { return birdRepository.findById(id); } }
BirdService
public interface BirdService { Bird get(Long id); }
报错信息
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'birdRepository' defined in com.nz.eagle.repository.BirdRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract com.nz.eagle.model.Bird com.nz.eagle.repository.BirdRepository.FindById(java.lang.Long)! Reason: Failed to create query for method public abstract com.nz.eagle.model.Bird com.nz.eagle.repository.BirdRepository.FindById(java.lang.Long)! No property 'findById' found for type 'Bird'!; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract com.nz.eagle.model.Bird com.nz.eagle.repository.BirdRepository.FindById(java.lang.Long)! No property 'findById' found for type 'Bird'!
问题原因与解决方法
原因
- JpaRepository已内置findById方法:
JpaRepository<Bird, Long>继承的父接口已经提供了findById方法,返回类型为Optional<Bird>,无需重复定义。 - 返回类型不兼容:你自定义的
Bird findById(Long Id)与父接口方法的返回类型(Optional<Bird>)不一致,导致Spring Data JPA无法正确解析方法规则,触发查询创建异常。
解决步骤
- 删除自定义的findById方法:修改BirdRepository,移除自己定义的查询方法,直接使用父接口提供的方法:
public interface BirdRepository extends JpaRepository<Bird, Long> { // 无需自定义findById,父接口已提供该方法 }
- Service层处理Optional返回值:由于父接口的
findById返回Optional<Bird>,需要在Service中处理空值场景,比如抛出异常或返回默认值:
@Override public Bird get(Long id) { // 若找不到对应Bird,抛出业务异常,可根据实际需求替换处理逻辑 return birdRepository.findById(id) .orElseThrow(() -> new IllegalArgumentException("Bird not found with id: " + id)); }
调整后即可正常使用Spring Data JPA自带的派生查询方法,同时解决报错问题。
内容的提问来源于stack exchange,提问作者Al Grant
相关产品推荐
相关产品推荐

