首页 文章

考虑在配置中定义类型为'javax.persistence.EntityManagerFactory'的bean

提问于
浏览
1

我使用的是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

如何解决这个问题?

3 回答

  • 0

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

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

    此代码将起作用:

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

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

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

    像这样:

    @Configuration
    public class BeanConfig {
    
        @PersistenceUnit
        EntityManagerFactory emf;
    
    }
    
  • 4

    如果你包含这个:

    <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 .

相关问题