多个数据源spring boot

时间:2018-05-25 16:21:58

标签: java spring-data-jpa

我已经尝试了小时来实现这一点,看看文档:

https://docs.spring.io/spring-boot/docs/current/reference/html/howto-data-access.html

...各种stackoverflow问题和我能找到的其他东西。但是,这证明是难以捉摸的(阅读,让我想把头撞在墙上)。任何帮助都是如此,所以欢迎!

我需要连接到两个不同的数据库(听起来很简单吗?)并且我有一个使用spring-boot-starter-data-jpa依赖关系的Spring Boot Web应用程序,它使用单个数据源非常好地 / em>的。现在我需要与第二个数据库交谈,但事情并没有奏效。我以为我已经工作了一段时间,但事实证明一切都是在主数据库中进行的。

我目前正试图让这项工作在一个单独的“减少”项目上,试图减少活动部件的数量,但仍然不能正常工作。

我有两个@Configuration类 - 每个数据源一个,这是第一个:

@Configuration
@EnableJpaRepositories(
        entityManagerFactoryRef = "firstEntityManagerFactory",
        transactionManagerRef = "firstTransactionManager",
        basePackages = {"mystuff.jpaexp.jpatest"})
public class DataConfiguration {
    @Bean
    @Primary
    @ConfigurationProperties(prefix = "app.datasource1")
    public DataSourceProperties firstDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @Primary
    @ConfigurationProperties("app.datasource1")
    public DataSource firstDataSource() {
        return firstDataSourceProperties().initializeDataSourceBuilder().
                driverClassName("org.postgresql.Driver").
                url("jdbc:postgresql://localhost:5432/experiment1").
                username("postgres").
                password("postgres").
                build();
    }

    @Primary
    @Bean
    public LocalContainerEntityManagerFactoryBean firstEntityManagerFactory() {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("mystuff.jpaexp.jpatest");
        factory.setDataSource(firstDataSource());
        factory.setPersistenceUnitName("ds1");
        return factory;
    }

    @Primary
    @Bean
    public PlatformTransactionManager firstTransactionManager() {
        return new JpaTransactionManager();
    }
}

这是第二个:

@Configuration
@EnableJpaRepositories(
        entityManagerFactoryRef = "secondEntityManagerFactory",
        transactionManagerRef = "secondTransactionManager",
        basePackages = {"mystuff.jpaexp.jpatest2"})
public class Otherconfiguration {
    @Bean
    @ConfigurationProperties(prefix = "app.datasource2")
    public DataSourceProperties secondDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @ConfigurationProperties("app.datasource2")
    public DataSource secondDataSource() {
        return secondDataSourceProperties().initializeDataSourceBuilder().
                driverClassName("org.postgresql.Driver").
                url("jdbc:postgresql://localhost:5432/experiment2").
                username("postgres").
                password("postgres").
                build();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean secondEntityManagerFactory() {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("mystuff.jpaexp.jpatest2");
        factory.setDataSource(secondDataSource());
        factory.setPersistenceUnitName("ds2");
        return factory;
    }

    @Bean
    public PlatformTransactionManager secondTransactionManager() {
        return new JpaTransactionManager();
    }
}

在两个软件包mystuff.jpaexp.jpatestmystuff.jpaexp.jpatest2的每一个中,我都有一个简单的@EntityCrudRepository,它们应该分别与第一个和第二个数据源一起使用。

然后我有一个main()来测试:

@SpringBootApplication
@EnableAutoConfiguration(exclude = {WebMvcAutoConfiguration.class})
@ComponentScan("mystuff.jpaexp.*")
public class SpringbootCommandLineApp implements CommandLineRunner {
    private final MyRepository myRepository;
    private final OtherRepo otherRepo;

    @Autowired
    public SpringbootCommandLineApp(MyRepository myRepository, OtherRepo otherRepo) {
        this.myRepository = myRepository;
        this.otherRepo = otherRepo;
    }

    public static void main(String[] args) {
        new SpringApplicationBuilder(SpringbootCommandLineApp.class)
                .web(false)
                .run(args);
    }

    @Override
    public void run(String... args) throws Exception {
        myRepository.save(new MyEntity("Goodbye or hello"));
        myRepository.save(new MyEntity("What?"));
        myRepository.save(new MyEntity("1,2,3..."));

        myRepository.findAll().forEach(System.out::println);

        otherRepo.save(new MyEntity2("J Bloggs"));
        otherRepo.save(new MyEntity2("A Beecher"));
        otherRepo.save(new MyEntity2("C Jee"));

        otherRepo.findAll().forEach(x -> {
            System.out.println("Name:" + x.getName() + ", ID: " + x.getId());
        });
    }
}

最后,application.properties中的一些道具:

app.datasource1.driver-class-name=org.postgresql.Driver
app.datasource1.url=jdbc:postgresql://localhost:5432/experiment1
app.datasource1.username=postgres
app.datasource1.password=postgres

app.datasource2.driver-class-name=org.postgresql.Driver
app.datasource2.url=jdbc:postgresql://localhost:5432/experiment2
app.datasource2.username=postgres
app.datasource2.password=postgres

这些完全没效果 - 事情似乎仍由spring.datasource.*配置,显然没用。

最终输出:

2018-05-25 17:04:00.797  WARN 29755 --- [           main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
2018-05-25 17:04:00.800  INFO 29755 --- [           main] utoConfigurationReportLoggingInitializer : 

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2018-05-25 17:04:00.803 ERROR 29755 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

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

Description:

Cannot determine embedded database driver class for database type NONE

Action:

If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).


Process finished with exit code 1

我知道这里有很多代码,对不起,谢谢!

1 个答案:

答案 0 :(得分:1)

好吧,花了很长时间,我认为有一些微妙的问题,还有一些可以简化的部分:

  • 只需要一个pin - 两个数据源都可以使用它
  • DataSource bean定义需要
  • DataSourceProperties,而不是@ConfigurationProperties bean
  • 认为 DataSourceProperties注释不正确,只用@ComponentScan("mystuff.jpaexp.*")替换它似乎修复了一些bean定义
  • 我必须在@ComponentScan定义中注入EntityManagerFactorJpaTransactionManager
  • 我添加了一个return new JpaTransactionManager(secondEntityManagerFactory().getObject()); bean,并明确将这些属性拖入JpaProperties

VendorAdapter / JpaProperties的变化看起来像这样(JpaProperties独立于供应商但它上面有一个hibernateProperties似乎很奇怪?!):

VendorAdapter

我认为这足以让事情顺利进行。此外,为了使嵌入式H2实例恢复生机,各种属性的永远如此聪明的默认不再有效,所以我还必须明确所有数据库属性:

@Bean
public LocalContainerEntityManagerFactoryBean secondEntityManagerFactory() {
    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setGenerateDdl(true);

    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(vendorAdapter);
    factory.setPackagesToScan("...entity-package...");
    factory.setDataSource(secondDataSource());
    Map<String, String> props = new HashMap<>();
    props.putAll(secondJpaProperties().getProperties());
    props.putAll(secondJpaProperties().getHibernateProperties(secondDataSource()));
    factory.setJpaPropertyMap(props);
    factory.setPersistenceUnitName("ds2");
    return factory;
}

@Bean
@ConfigurationProperties(prefix = "jpa.datsource2")
public JpaProperties secondJpaProperties() {
    return new JpaProperties();
}