简体   繁体   English

如何在spring中使用多个数据库?

[英]How to use multiple databases with spring?

i need to create web-app (with spring+mysql) which should be a little like "MySQL Workbench online" .我需要创建网络应用程序(使用 spring+mysql),它应该有点像“MySQL Workbench online” In my application, Users will be able to create their own databases.在我的应用程序中,用户将能够创建自己的数据库。 I did it as follows:我是这样做的:

User press (button for example) 'create new database' and after that I create a file.sql and write the following code to it:用户按下(例如按钮)“创建新数据库”,然后我创建一个 file.sql 并将以下代码写入其中:

CREATE SCHEMA 'db_name';创建架构'db_name';

If user choose option "create table" i will open this file again and I will write proper code to it如果用户选择选项“创建表”,我将再次打开此文件,并向其写入正确的代码

After all of that when user finally finish his database i have file.sql when i have all SQL code which need to be execute in my java code... Well and the things start to get complicated, here is my question:毕竟,当用户最终完成他的数据库时,当我拥有需要在我的 java 代码中执行的所有 SQL 代码时,我有 file.sql ......好吧,事情开始变得复杂,这是我的问题:

This is my datasource in application.properties:这是我在 application.properties 中的数据源:

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

If you look at that i didnt specify database, i only choose port i have connection only to server not to a specific database.如果你看我没有指定数据库,我只选择我只连接到服务器而不是特定数据库的端口。 Can i do some operation on databases if i didnt specify single specific database?如果我没有指定单个特定的数据库,我可以对数据库进行一些操作吗? Before that i had that configuration:在此之前,我有这样的配置:

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

Everything worked fine, for example: my select looked like that:一切正常,例如:我的选择看起来像这样:

Select * from table1;从表1中选择*;

Can i change datasource from localhost:3306/mydatabase to: localhost:3306/ and execute that select?我可以将数据源从 localhost:3306/mydatabase 更改为:localhost:3306/ 并执行该选择吗?

Select * from mydatabase.table1;从 mydatabase.table1 中选择 *;

If i can what else i need to configure?如果可以,我还需要配置什么? I all time have errors "No database selected".我总是有错误“没有选择数据库”。

(I need get connection only to server not to a specific database because i want to execute sql code "Create schema" in java code) (我只需要连接到服务器而不是特定数据库,因为我想在 java 代码中执行 sql 代码“创建模式”)

Spring Boot simplifies the configuration of datasource. Spring Boot 简化了数据源的配置。

By default, Spring Boot will instantiate its default DataSource with the configuration properties prefixed by spring.datasource.*:默认情况下,Spring Boot 将使用以 spring.datasource.* 为前缀的配置属性实例化其默认数据源:

spring.datasource.jdbcUrl = [url]
spring.datasource.username = [username]
spring.datasource.password = [password]

We now want to keep on using the same way to configure the second DataSource, but with a different property namespace:我们现在想继续使用相同的方式来配置第二个数据源,但具有不同的属性命名空间:

spring.second-datasource.jdbcUrl = [url]
spring.second-datasource.username = [username]
spring.second-datasource.password = [password]

Because we want the Spring Boot autoconfiguration to pick up those different properties (and actually instantiate two different DataSources), we'll define 2 configuration classes similar to the ones in the previous sections:因为我们希望 Spring Boot 自动配置选择这些不同的属性(并实际实例化两个不同的数据源),所以我们将定义 2 个类似于前几节中的配置类:

@Configuration
@PropertySource({"classpath:persistence-multiple-db-boot.properties"})
@EnableJpaRepositories(
  basePackages = "com.myProj.multipledb.dao.user",
  entityManagerFactoryRef = "userEntityManager",
  transactionManagerRef = "userTransactionManager")
public class PersistenceUserAutoConfiguration {

    @Primary
    @Bean
    @ConfigurationProperties(prefix="spring.datasource")
    public DataSource userDataSource() {
        return DataSourceBuilder.create().build();
    }
    // userEntityManager bean 

    // userTransactionManager bean
}

And then this然后这个

@Configuration
@PropertySource({"classpath:persistence-multiple-db-boot.properties"})
@EnableJpaRepositories(
  basePackages = "com.myProj.multipledb.dao.product", 
  entityManagerFactoryRef = "productEntityManager", 
  transactionManagerRef = "productTransactionManager")
public class PersistenceProductAutoConfiguration {

    @Bean
    @ConfigurationProperties(prefix="spring.second-datasource")
    public DataSource productDataSource() {
        return DataSourceBuilder.create().build();
    }

    // productEntityManager bean 

    // productTransactionManager bean
}

We have defined the data source properties inside persistence-multiple-db-boot.properties according to the Boot auto-configuration convention.我们已经根据引导自动配置约定在persistence-multiple-db-boot.properties 中定义了数据源属性。

The interesting part is annotating the data source bean creation method with @ConfigurationProperties.有趣的部分是使用@ConfigurationProperties 注释数据源 bean 创建方法。 We just need to specify the corresponding config prefix.我们只需要指定相应的配置前缀。 Inside this method, we're using a DataSourceBuilder, and Spring Boot will automatically take care of the rest.在这个方法中,我们使用了一个 DataSourceBuilder,Spring Boot 会自动处理剩下的事情。 But how do the configured properties actually get injected into the DataSource configuration?但是如何将配置的属性实际注入到 DataSource 配置中呢?

When calling the build() method on the DataSourceBuilder, it'll call its private bind() method:在 DataSourceBuilder 上调用 build() 方法时,它将调用其私有 bind() 方法:

public T build() {
    Class<? extends DataSource> type = getType();
    DataSource result = BeanUtils.instantiateClass(type);
    maybeGetDriverClassName();
    bind(result);
    return (T) result;
}

This private method performs much of the autoconfiguration magic, binding the resolved configuration to the actual DataSource instance:这个私有方法执行了许多自动配置魔法,将解析的配置绑定到实际的 DataSource 实例:

private void bind(DataSource result) {
    ConfigurationPropertySource source = new MapConfigurationPropertySource(this.properties);
    ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases();
    aliases.addAliases("url", "jdbc-url");
    aliases.addAliases("username", "user");
    Binder binder = new Binder(source.withAliases(aliases));
    binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(result));

Although we don't have to touch any of this code ourselves, it's still useful to know what's happening under the hood of the Spring Boot autoconfiguration.虽然我们不必自己接触任何这些代码,但了解 Spring Boot 自动配置背后发生的事情仍然很有用。

Besides this, the Transaction Manager and Entity Manager beans configuration is the same as the standard Spring application.除此之外,事务管理器和实体管理器 bean 配置与标准 Spring 应用程序相同。

kindly refer the below link for an example: https://medium.com/@joeclever/using-multiple-datasources-with-spring-boot-and-spring-data-6430b00c02e7请参考以下链接作为示例: https : //medium.com/@joeclever/using-multiple-datasources-with-spring-boot-and-spring-data-6430b00c02e7

A microservices architecture solve your problem.微服务架构可以解决您的问题。 Using Spring is more easy to create it.使用 Spring 更容易创建它。

In short, you will create one database (called gateway ) and other databases for your services.简而言之,您将为您的服务创建一个数据库(称为gateway )和其他数据库。 All requests go through the gateway to other databases.所有请求都通过网关到达其他数据库。

Read this article for more information!阅读这篇文章了解更多信息! ⬇️ ⬇️

https://spring.io/blog/2015/07/14/microservices-with-spring https://spring.io/blog/2015/07/14/microservices-with-spring

Moreover, if you search there are more guides.此外,如果您搜索,还有更多指南。

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

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