Spring data jpa- No bean named 'entityManagerFactory' is defined; Injection of autowired dependencies failed

前端 未结 8 1227
鱼传尺愫
鱼传尺愫 2020-11-27 15:19

I\'m developing application using spring data jpa,hibernate,mysql,tomcat7,maven and it\'s create error.I\'m trying to figure it out but i failed.

error are Cannot

相关标签:
8条回答
  • 2020-11-27 15:44

    I think this is related to the newer version of spring boot plus using spring data JPA just replace @Bean annotation above public LocalContainerEntityManagerFactoryBean entityManagerFactory() to @Bean(name="entityManagerFactory")

    Determining the name of bean should solve the issue

    0 讨论(0)
  • 2020-11-27 15:57

    I had this issue after migrating from spring-boot-starter-data-jpa ver. 1.5.7 to 2.0.2 (from old hibernate to hibernate 5.2). In my @Configuration class I injected entityManagerFactory and transactionManager.

    //I've got my data source defined in application.yml config file, 
    //so there is no need to configure it from java.
    @Autowired
    DataSource dataSource;
    
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        //JpaVendorAdapteradapter can be autowired as well if it's configured in application properties.
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(false);
    
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        //Add package to scan for entities.
        factory.setPackagesToScan("com.company.domain");
        factory.setDataSource(dataSource);
        return factory;
    }
    
    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory);
        return txManager;
    }
    

    Also remember to add hibernate-entitymanager dependency to pom.xml otherwise EntityManagerFactory won't be found on classpath:

    <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.0.12.Final</version>
    </dependency>
    
    0 讨论(0)
提交回复
热议问题