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

新手上路,请多包涵

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

如何解决这个问题?

原文由 James Grey 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
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> {
}

where Actor is a JPA entity class and Integer is the ID / primary key and inject ActorDao in a service 实施类。

原文由 ootero 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题