【问题标题】:Consider defining a bean of type 'javax.persistence.EntityManagerFactory' in your configuration考虑在配置中定义“javax.persistence.EntityManagerFactory”类型的 bean
【发布时间】:2018-02-20 15:23:20
【问题描述】:

我正在使用 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

如何解决这个问题?

【问题讨论】:

标签: java spring hibernate spring-boot hibernate-5.x


【解决方案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> {
}

其中ActorJPA 实体类,Integer 是ID / 主键并在service impl 类中注入ActorDao

【讨论】:

  • 我倾向于使用全功能的 Hibernate。在提问之前,我用 Spring Boot 2.0.0.RC1 成功创建了 Hibernate 的 JPA 实现。
  • 我没有收到您的评论,但同样,如果您在您的pom 中包含spring-boot-starter-data-jpa,则无需明确提供EntityManagerFactory 和/或SessionFactory豆子。 Spring Boot 根据类路径和配置属性中的依赖关系为您提供它们。顺便说一句,您的Application.java 中缺少@EnableJpaRepositories
【解决方案2】:

您遇到的具体错误是由@Qualifier 注释引起的; Spring 正在寻找具有您提到的特定名称的 Bean,而不是寻找任何 EntityManagerFactory 类型的 Bean。只需删除注释即可。

然而,一旦你修复了这个问题,并且因为你也在构造 SessionFactory 的方法中注入了 Bean,Spring Boot 将产生另一个与循环依赖相关的错误。为避免这种情况,只需从 sessionFactory 方法中完全删除参数,因为您已经在 Config 类中注入了 EntityManagerFactory

此代码将起作用:

@Bean
public SessionFactory sessionFactory() {
        return emf.unwrap(SessionFactory.class);
}

【讨论】:

【解决方案3】:

BeanConfig 中,您应该通过@PersistenceUnit 注入JPA EntityManager,而不是@Autowired

并删除 getSessionFactory,因为 Hibernate SessionFactory 已在内部创建,您始终可以打开 EntityManagerFactory

像这样:

@Configuration
public class BeanConfig {

    @PersistenceUnit
    EntityManagerFactory emf;

}

【讨论】:

猜你喜欢
  • 2021-09-22
  • 2017-03-19
  • 2018-08-27
  • 2018-06-22
  • 1970-01-01
  • 2020-08-01
  • 2019-02-14
  • 2018-12-21
  • 2019-05-10
相关资源
最近更新 更多