Java 考虑定义一个类型的豆和*x27;EntityManagerFactory';在您的配置中
我使用的是SpringBoot2.0.0.RC1(包括SpringFramework 5.0.3.RELEASE)、Hibernate5.2.12.Final、JPA2.1API 1.0.0.Final 我有一节课Java 考虑定义一个类型的豆和*x27;EntityManagerFactory';在您的配置中,java,spring,hibernate,spring-boot,hibernate-5.x,Java,Spring,Hibernate,Spring Boot,Hibernate 5.x,我使用的是SpringBoot2.0.0.RC1(包括SpringFramework 5.0.3.RELEASE)、Hibernate5.2.12.Final、JPA2.1API 1.0.0.Final 我有一节课 package com.example; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springfra
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
如何修复此问题?您所遇到的特定错误是由
@限定符
注释引起的;Spring正在寻找具有您提到的特定名称的Bean,而不是寻找类型为EntityManagerFactory
的任何Bean。只需删除注释即可
但是,一旦您修复了这个问题,并且因为您还在构造SessionFactory的方法中注入Bean,Spring Boot将生成另一个与循环依赖项相关的错误。为了避免这种情况,只需从sessionFactory
方法中删除该参数,因为您已经在Config类中注入了EntityManagerFactory
此代码将在以下情况下工作:
@Bean
public SessionFactory sessionFactory() {
return emf.unwrap(SessionFactory.class);
}
如果包括以下内容:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
其中,
Actor
是一个JPA
实体类,Integer
是ID/主键,在服务impl类中注入ActorDao
。在BeanConfig
中,您应该通过@PersistenceUnit
而不是@Autowired
注入JPA实体管理器
并删除getSessionFactory
,因为Hibernate SessionFactory已经在内部创建,您可以随时打开EntityManagerFactory
像这样:
@Configuration
public class BeanConfig {
@PersistenceUnit
EntityManagerFactory emf;
}
您是否使用任何spring启动程序作为依赖项?是的,我倾向于使用全功能Hibernate。在提出问题之前,我使用Spring Boot 2.0.0.RC1成功创建了Hibernate的JPA实现。我没有收到您的评论,但是,如果您在pom
中包含Spring Boot starter数据JPA
,则无需显式提供EntityManagerFactory
和/或SessionFactory
beanSpring Boot
根据类路径和配置属性中的依赖项为您提供了它们。顺便说一句,您的应用程序中缺少@EnableJpaRepositories
。java
我对它进行了测试,它与您的POM文件一起工作。您有什么错误?应用代码后,这是JDK 9可能发生的控制台日志错误,但我不确定,因为我现在没有机会测试。非常感谢!我发现了错误:这不是,仍然是错误的。我添加了一个关于BeanConfig
的示例。非常感谢!我在课堂上遇到了问题。使用EntityManagerFactory时
如何查询?我猜你没看过说明书吧?您需要使用@PersistenceContext注入JPA EntityManager。是的,对不起,我没有仔细阅读用户手册。请为我指出!
@Configuration
public class BeanConfig {
@PersistenceUnit
EntityManagerFactory emf;
}