字段存储库需要找不到名为'entityManagerFactory'的bean

时间:2018-09-19 09:15:58

标签: spring-boot jpa gradle spring-data-jpa build.gradle

我花了几天时间尝试解决此错误,但没有成功。我正在尝试配置两个数据库并写入它们。

我看着:

https://medium.com/@joeclever/using-multiple-datasources-with-spring-boot-and-spring-data-6430b00c02e7

https://www.baeldung.com/spring-data-jpa-multiple-databases

https://www.devglan.com/spring-boot/spring-boot-multiple-database-configuration

https://raymondhlee.wordpress.com/2015/10/31/configuring-multiple-jpa-entity-managers-in-spring-boot/

https://github.com/igormukhin/spring-boot-sample-data-jpa-multiple/blob/master/src/main/java/sample/data/jpa/Database1Configuration.java 此外,还有大量来自SO的错误或类似示例链接。

这是我的代码:

fromDB.datasource.url=jdbc:h2:file:D:/test1/db1
fromDB.datasource.username=sa
fromDB.datasource.password=
fromDB.datasource.platform=h2
fromDB.datasource.driverClassName=org.h2.Driver

toDB.datasource.url=jdbc:h2:file:D:/test2/db2
toDB.datasource.username=sa
toDB.datasource.password=
toDB.datasource.platform=h2
toDB.datasource.driverClassName=org.h2.Driver

spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.h2.console.settings.trace=true
spring.h2.console.settings.web-allow-others=true
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

休眠设置-hibernate.properties

spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.use_sql_comments=false
spring.jpa.properties.hibernate.format_sql=true
spring.datasource.initialization-mode=always
spring.datasource.initialize=true
spring.jpa.generate-ddl=true

ConfigClasses

    @Configuration
    @EnableTransactionManagement
    @EnableJpaRepositories(
        entityManagerFactoryRef = "toEntityManager",
        transactionManagerRef = "toTransactionManager",
        basePackages = "leadTime.service"
    )
    public class ToDBConfig {

      @Bean
      @ConfigurationProperties(prefix = "toDB.datasource")
      public DataSource toDataSource() {
        return DataSourceBuilder
            .create()
            .build();
      }

      @Bean(name = "toEntityManager")
      public LocalContainerEntityManagerFactoryBean toEntityManagerFactory(
          EntityManagerFactoryBuilder builder) {
        return builder
            .dataSource(toDataSource())
            .properties(hibernateProperties())
            .packages(TestDataTo.class)
            .persistenceUnit("to")
            .build();
      }

      @Bean(name = "toTransactionManager")
      public PlatformTransactionManager toTransactionManager(@Qualifier("toEntityManager") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
      }

      private Map hibernateProperties() {

        Resource resource = new ClassPathResource("hibernate.properties");

        try {
          Properties properties = PropertiesLoaderUtils.loadProperties(resource);

          return properties.entrySet().stream()
              .collect(Collectors.toMap(
                  e -> e.getKey().toString(),
                  e -> e.getValue())
              );
        } catch (IOException e) {
          return new HashMap();
        }
      }
    }

第二个configClass

    @Configuration
    @EnableTransactionManagement
    @EnableJpaRepositories(
        entityManagerFactoryRef = "fromEntityManager",
        transactionManagerRef = "fromTransactionManager",
        basePackages = "leadTime.service"
    )
    public class FromDBConfig {

      @Primary
      @Bean
      @ConfigurationProperties(prefix = "fromDB.datasource")
      public DataSource fromDataSource() {
        return DataSourceBuilder
            .create()
            .build();
      }

      @Primary
      @Bean(name = "fromEntityManager")
      public LocalContainerEntityManagerFactoryBean fromEntityManagerFactory(
          EntityManagerFactoryBuilder builder) {
        return builder
            .dataSource(fromDataSource())
            .properties(hibernateProperties())
            .packages(TestDataFrom.class)
            .persistenceUnit("from")
            .build();
      }

      @Primary
      @Bean(name = "fromTransactionManager")
      public PlatformTransactionManager fromTransactionManager(@Qualifier("fromEntityManager") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
      }

      private Map hibernateProperties() {

        Resource resource = new ClassPathResource("hibernate.properties");

        try {
          Properties properties = PropertiesLoaderUtils.loadProperties(resource);

          return properties.entrySet().stream()
              .collect(Collectors.toMap(
                  e -> e.getKey().toString(),
                  e -> e.getValue())
              );
        } catch (IOException e) {
          return new HashMap();
        }
      }}

存储库:

    public interface ToRepository extends CrudRepository<TestDataTo, Integer> 
    {

      @Override
      TestDataTo save(TestDataTo testDataTo);
    }

DataInit:

    @Component
    public class DataInit {
      @Autowired
      ToRepository toRepository;

      @Autowired
      FromRepository fromRepository;

      @Transactional("fromTransactionManager")
      public void insertDataIntoFromDB() throws SQLException {
        TestDataFrom testDataFrom = new TestDataFrom();
        testDataFrom.setId(1);
        testDataFrom.setName("Test");
        fromRepository.save(testDataFrom);

      }
      //
      @Transactional("toTransactionManager")
      public void insertDataIntoToDB() throws SQLException {

        TestDataTo testDataTo = new TestDataTo();
        testDataTo.setId(1);
        testDataTo.setName("Ale");
        toRepository.save(testDataTo);
      }
    }

MainClass:

    @EnableTransactionManagement
    @SpringBootApplication
    public class LeadTimeApplication  {
      private Logger LOG = LoggerFactory.getLogger("LeadTimeApplication");

      @Autowired
      ToRepository toRepository;

      @Autowired
      FromRepository fromRepository;

      public static void main(String[] args) {
        SpringApplication.run(LeadTimeApplication.class, args);

      }

      @Autowired DataInit initializer;

      @PostConstruct
      public void init() throws  SQLException{

        initializer.insertDataIntoFromDB();
        initializer.insertDataIntoToDB();

      }

错误:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field toRepository in leadTime.LeadTimeApplication 
required a bean named 'entityManagerFactory' that could not be found.


Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.

我尝试过: 使用

@EnableAutoConfiguration(exclude = { JpaRepositoriesAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class})

老实说,我不知道该怎么办,我使用不同的方法多次重写了这段代码,但没有成功。如果我任职于他,没有配置新的entityManager和事务,也没有使用@Transactional,那么该应用程序正在运行(已创建2个DB),但是两个表都在同一个DB中创建(当然)

添加了gradle配置

//Spring dependencies
compile "org.springframework.boot:spring-boot-starter- 
actuator:${springBootVersion}"
compile "org.springframework.boot:spring-boot-starter- 
web:${springBootVersion}"
compile "org.springframework.boot:spring-boot-starter- 
logging:${springBootVersion}"
compile "org.springframework.boot:spring-boot-configuration- 
processor:${springBootVersion}"


//JPA dependency
compile "org.springframework.boot:spring-boot-starter-data- 
jpa:${springBootVersion}"

testCompile "com.oracle:ojdbc7:12.1.0.2"
testCompile 'com.h2database:h2:1.4.194'
runtime 'com.h2database:h2:1.4.194'
//  compile group: 'h2', name: 'h2', version: '0.2.0'

compile group: 'org.hibernate', name: 'hibernate-entitymanager'
//compile group: 'org.hibernate', name: 'hibernate-gradle-plugin', version: 
'5.3.6.Final'
// https://mvnrepository.com/artifact/org.hibernate/hibernate-core
compile group: 'org.hibernate', name: 'hibernate-core'

1 个答案:

答案 0 :(得分:0)

根据您粘贴的内容

https://medium.com/@joeclever/using-multiple-datasources-with-spring-boot-and-spring-data-6430b00c02e7

其中一个darasource被配置为“默认”,另一个被命名。您正在创建两个带有fromto前缀的“命名” bean。 更改from的{​​{1}}数据库定义entityManager,应该没问题。

我不知道内部原理,但是就常识而言,您尝试的方法应该可以工作,实际上,应用程序配置程序需要一些默认数据源,因此会出现错误。

相关问题