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

前端 未结 8 1333
鱼传尺愫
鱼传尺愫 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: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:

    
            org.hibernate
            hibernate-entitymanager
            5.0.12.Final
    
    

提交回复
热议问题