简体   繁体   English

Spring boot JPA如何从同一个连接添加多个数据库?

[英]Spring boot JPA how to add multiple databases from same connection?

I have two different mysql database from the same connection and would like to use both in my application.properties like this way:我有来自同一个连接的两个不同的 mysql 数据库,并希望在我的 application.properties 中使用它们,如下所示:

spring.datasource.url=jdbc:mysql://localhost:3306/membership
spring.datasource.username=root
spring.datasource.password=

spring.datasource.url=jdbc:mysql://localhost:3306/finance
spring.datasource.username=root
spring.datasource.password=

But this is not allowed (duplicate key's).但这是不允许的(重复密钥)。 I have found this guide but this is to much code i think not a elegant solution, looks like workaround for simple problem.我找到了本指南,但我认为这是很多代码,不是一个优雅的解决方案,看起来像是解决简单问题的方法。 Are there better and much simpler solutions?有没有更好更简单的解决方案?

PS: I am new to spring boot. PS:我是弹簧靴的新手。

You have to decleare different keys for different datasource.您必须为不同的数据源清除不同的键。 The main config for multi datasource is(this is the demo):多数据源的主要配置是(这是演示):

@Bean
@Primary
@ConfigurationProperties("app.datasource.foo")
public DataSourceProperties fooDataSourceProperties() {
    return new DataSourceProperties();
}

@Bean
@Primary
@ConfigurationProperties("app.datasource.foo")
public DataSource fooDataSource() {
    return fooDataSourceProperties().initializeDataSourceBuilder().build();
}

@Bean
@ConfigurationProperties("app.datasource.bar")
public DataSourceProperties barDataSourceProperties() {
    return new DataSourceProperties();
}

@Bean
@ConfigurationProperties("app.datasource.bar")
public DataSource barDataSource() {
    return barDataSourceProperties().initializeDataSourceBuilder().build();
}

You can refer to this link and the post to have an overview for the configuration.您可以参考此链接帖子以了解配置概览。

I think you can use only 1 MySQL database.我认为您只能使用 1 个 MySQL 数据库。 Try to combine with PostgreSQL.尝试与 PostgreSQL 结合。 Example 例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM