【问题标题】:Spring Boot: Configure h2 jdbc urlSpring Boot:配置 h2 jdbc url
【发布时间】:2020-12-22 11:54:51
【问题描述】:

spring boot 配置中的内存数据库工作正常,代码如下。但是 url 不是从 YAML 配置中获取的。虽然 h2 控制台 已启用

在日志中,url 打印为内存数据库。

  1. 如何将 jdbc url 从内存更改为文件。

日志文件

2020-09-03 14:22:42.595 [RMI TCP Connection(2)-10.44.33.51] 调试 o.s.jdbc.datasource.DataSourceUtils - 从数据源获取 JDBC 连接

2020-09-03 14:22:42.595 [RMI TCP Connection(2)-10.44.33.51] 调试 osjdSimpleDriverDataSource - 创建到 [jdbc:h2:mem:testdb;MODE=Oracle;DB_CLOSE_DELAY= 的新 JDBC 驱动程序连接-1;DB_CLOSE_ON_EXIT=false]

@Configuration
public class DataSourceConfiguration {

@Bean
@Primary
public DataSource dataSource() {
    return new EmbeddedDatabaseBuilder()
            .setType(EmbeddedDatabaseType.H2)
            .setName("testdb;MODE=Oracle")
            .addScript("classpath:sql/Create-table.sql")
            .build();
}
}

YAML 配置

  spring:
      h2:
        console:
          enabled: true
          path: /h2
      datasource:
        url: jdbc:h2:file:C:/db/test
        username: test
        password: password
        driverClassName: org.h2.Driver

【问题讨论】:

  • 这可能是因为您覆盖了 DataSource bean。
  • 是的,我想在启动时运行脚本,所以覆盖了数据源 bean。同时我也想传递 url

标签: java spring spring-boot h2


【解决方案1】:

不要定义dataSource bean。通过属性文件配置datasource。如果您想在应用启动时执行DDL 和/或DML sql 脚本,您可以执行以下操作:

spring:
  datasource:
    url: jdbc:h2:file:C:/db/test
    username: test
    password: password
    schema: classpath:sql/Create-table.sql
    data: classpath:sql/fill-table.sql

默认情况下,Spring Boot 在应用程序类路径的根目录中查找文件 schema.sqldata.sql(例如 src/main/resources/schema.sql),但您可以在属性 spiring.datasource.schema 中覆盖此行为>spring.datasource.data 就像上面的代码示例一样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-30
    • 2018-03-22
    • 2019-10-08
    • 2016-05-15
    • 1970-01-01
    • 2019-10-21
    • 1970-01-01
    相关资源
    最近更新 更多