錯誤:
在Springboot 框架中使用JPA的過程中,怎么來實現數據庫操作底層的交互呢?Spring JPA其實已經提供了一套很全面的解決方案,實現對數據庫的增、刪、查、改只需要繼承JPA實現類:
org.springframework.data.jpa.repository.query.SimpleJpaRepository
或者直接繼承JPA提供的接口:
org.springframework.data.jpa.repository.JpaRepository
org.springframework.data.jpa.repository.CrudRepository
使用實現類:SimpleJpaRepository時,本人覺得並不是很方便,不如使用其擴展出來的接口方便。但是在使用接口的過程中,遇到了一個問題,如下:
No qualifying bean of type 'xxx.xxx.xxx' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
或:
Not a managed type: class xxx.xxx.xxx
其實導致這個異常的原因很簡單,就是因為Springboot未能正常將其掃描並沒注入到容器中。而且一般在使用Springboot的初始框架中,啟動類位置於所有Service,Entity,Controller或者其它類的最上層的話,這個問題很少會出現。
解決方案:
方案一、把 @SpringBootApplication 注解的 SpringBoot 入口類移到上層 root 包中,使 JpaRepository 子接口位於 root 包及其子包中。
方案二、在 SpringBoot 入口類上添加
(1) @ComponentScan(basePackages = "xxx.xxx.xxx"):掃描 @Controller、@Service 注解;
(2) @EnableJpaRepositories(basePackages = "xxx.xxx.xxx"):掃描 @Repository 注解;
(3) @EntityScan(basePackages = "xxx.xxx.xxx"):掃描 @Entity 注解;
https://blog.csdn.net/u011659172/article/details/51537602
https://blog.csdn.net/zhongzh86/article/details/54313706
https://blog.csdn.net/andy_zhang2007/article/details/84064862