【问题标题】:How to connect to a postgresql database "on the fly" using Spring Boot如何使用 Spring Boot “即时”连接到 postgresql 数据库
【发布时间】:2020-01-12 06:35:30
【问题描述】:

我知道如何以通常的方式连接到数据库。我需要的是在运行时选择要连接的数据库。

我有一个默认数据库(由系统使用)和许多其他选项供用户选择获取数据。这意味着没有任何实体或 JPA 映射。

以前我用这个:

  try (Connection connection = DriverManager.getConnection(connectionString, user, password);
  PreparedStatement preparedStatement = connection.prepareStatement(nativeQuery)) {

  preparedStatement.setString( 1, coordinate );

  try (ResultSet resultSet = preparedStatement.executeQuery()) {
    while (resultSet.next())
       result = resultSet.getString(RESULT_PARAM);
    }
  } catch (SQLException ex) {
    CodeUtils.log(QUERY_ERROR_MSG, this);
    CodeUtils.log(ex.getMessage(), this);
  }

但我不知道如何将它移植到 Spring Boot。

【问题讨论】:

标签: spring postgresql spring-boot jpa


【解决方案1】:

您可以如下定义数据库配置-

@Configuration
public class MyDBConfig {
    @Bean("db1Ds")
    @Primary
    @ConfigurationProperties("app.ds.db1")
    public DataSource db1DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean("db2Ds")
    @ConfigurationProperties("app.ds.db2")
    public DataSource db2DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean("db1JdbcTemplate")
    @Autowired
    public JdbcTemplate db1JdbcTemplate(@Qualifier("db1Ds") DataSource ds) {
        return new JdbcTemplate(ds);
    }

    @Bean("db2JdbcTemplate")
    @Autowired
    public JdbcTemplate db2JdbcTemplate(@Qualifier("db2Ds") DataSource ds) {
        return new JdbcTemplate(ds);
    }
}

根据用户的选择切换 Jdbc 模板。

官方文档: https://docs.spring.io/spring-boot/docs/current/reference/html/howto-data-access.html#howto-two-datasources

【讨论】:

  • 我做不到。用户将决定他将连接到的数据库/服务器。我不会向他提供诸如“您可以连接到 db1 或 db2”之类的选项列表。用户将告诉系统“连接到数据库 URL/USER/PASSWORD 并为我提供此查询的 JSON 数据”......类似于这个。但是这个链接完全按照我需要的方式解决了这个问题。stackoverflow.com/questions/52845453/…。我发现没有必要改变我以前做过的任何事情。
猜你喜欢
  • 2018-06-09
  • 1970-01-01
  • 2020-07-29
  • 2019-06-15
  • 2019-12-26
  • 1970-01-01
  • 2019-06-12
  • 2021-02-09
  • 2018-10-10
相关资源
最近更新 更多