【问题标题】:Check if H2 db file exists检查 H2 db 文件是否存在
【发布时间】:2018-11-22 06:59:24
【问题描述】:

我一直在文件上使用真正简单的 H2 DB。我的设置是这样的:

Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:"+dbFileName);
Statement stat = conn.createStatement();

在应用程序启动时,我会这样做:

File dbFile = new File("~/mydb.db");
if(!dbFile.exists()) {
   String sql = -create my table here, etc...
}

但我现在正尝试以“正确”的 Spring Boot 方式执行此操作。所以我有我的 application.properties 文件来包含这个:

# H2
spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.datasource.url=jdbc:h2:file:~/mydb.db
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver

我正在尝试使用 JdbcTemplate / Dao 的做事方式。但我需要检查数据库在启动时是否存在。所以我想在 ApplicationReadyEvent 的应用程序类事件侦听器中进行之前的检查。但是如何获得对数据源 url 的引用?我之前有一个配置属性,并且是自动加载的,我仍然可以这样做,但它会在某些地方,那会很糟糕。

那么当应用程序启动时,确保此 DB 文件存在的散文家/正确方法是什么。 (我希望以 JDBC 方式进行,请不要使用 JPA)

【问题讨论】:

    标签: java spring spring-boot h2 spring-jdbc


    【解决方案1】:

    你可以使用ApplicationListener然后解析spring.datasource.url值:

    import java.io.File;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.context.event.ApplicationStartedEvent;
    import org.springframework.context.ApplicationListener;
    import org.springframework.stereotype.Component;
    
    @Component
    public class MyApplicationListener implements ApplicationListener<ApplicationStartedEvent> {
    
        @Value("${spring.datasource.url}")
        private String databaseUrl;
    
        @Override
        public void onApplicationEvent(ApplicationStartedEvent event) {
            System.out.println("Application started");
            String path = databaseUrl.replace("jdbc:h2:file:", "");
            System.out.println(path);
            File dbFile = new File(path);
            if (!dbFile.exists()) {
                String sql = "etc";
            }
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-22
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多