![](/img/trans.png)
[英]A component required a bean of type 'javax.persistence.EntityManagerFactory' that could not be found
[英]Consider defining a bean of type 'javax.persistence.EntityManagerFactory' in your configuration
我使用的是Spring Boot 2.0.0.RC1(包括Spring Framework 5.0.3.RELEASE),Hibernate 5.2.12.Final,JPA 2.1 API 1.0.0.Final。
我上課了
package com.example;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.persistence.EntityManagerFactory;
@Configuration
public class BeanConfig {
@Autowired
EntityManagerFactory emf;
@Bean
public SessionFactory sessionFactory(@Qualifier("entityManagerFactory") EntityManagerFactory emf) {
return emf.unwrap(SessionFactory.class);
}
}
然后錯誤
Error
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of method sessionFactory in com.example.BeanConfig required a bean of type 'javax.persistence.EntityManagerFactory' that could not be found.
Action:
Consider defining a bean of type 'javax.persistence.EntityManagerFactory' in your configuration.
Process finished with exit code 1
如何解決這個問題?
如果你包含這個:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
您不必自動裝配Entity Manager
或提供Session Factory
bean。
您只需要提供JpaRepository接口,例如:
public interface ActorDao extends JpaRepository<Actor, Integer> {
}
其中Actor
是JPA
實體類, Integer
是ID /主鍵,並在service
impl類中注入ActorDao
。
您遇到的具體錯誤是由@Qualifier
注釋引起的; Spring正在尋找具有您提到的特定名稱的Bean,而不是尋找任何類型為EntityManagerFactory
Bean。 只需刪除注釋即可。
但是,一旦你修復了它,並且因為你也在構造SessionFactory的方法中注入了Bean,Spring Boot將生成另一個與循環依賴相關的錯誤。 為了避免這種情況,只需從sessionFactory
方法中完全刪除參數,因為您已經在Config類中注入了EntityManagerFactory
。
此代碼將起作用:
@Bean
public SessionFactory sessionFactory() {
return emf.unwrap(SessionFactory.class);
}
在BeanConfig
,您應該通過@PersistenceUnit
注入JPA EntityManager
,而不是@Autowired
。
並刪除了getSessionFactory
因為Hibernate SessionFactory已在內部創建,您始終可以解包EntityManagerFactory
。
像這樣:
@Configuration
public class BeanConfig {
@PersistenceUnit
EntityManagerFactory emf;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.