我使用的是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
如何解决这个问题?
答案 0 :(得分:6)
如果你包含这个:
<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 /主键,并在ActorDao
impl类中注入service
。
答案 1 :(得分:0)
您遇到的具体错误是由@Qualifier
注释引起的; Spring正在寻找具有您提到的特定名称的Bean,而不是查找类型EntityManagerFactory
的任何Bean。只需删除注释即可。
但是,一旦你修复了它,并且因为你也在构造SessionFactory的方法中注入了Bean,Spring Boot将生成另一个与循环依赖相关的错误。为避免这种情况,只需从sessionFactory
方法中完全删除参数,因为您已在Config类中注入了EntityManagerFactory
。
此代码可以使用:
@Bean
public SessionFactory sessionFactory() {
return emf.unwrap(SessionFactory.class);
}
答案 2 :(得分:0)
在BeanConfig
中,您应该通过EntityManager
注入JPA @PersistenceUnit
,而不是@Autowired
。
并删除getSessionFactory
,因为Hibernate SessionFactory已在内部创建,您始终可以打开EntityManagerFactory
。
像这样:
@Configuration
public class BeanConfig {
@PersistenceUnit
EntityManagerFactory emf;
}