检查H2 db文件是否存在

Check if H2 db file exists

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

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...
}

但我现在正尝试以 "correct" Spring 引导方式执行此操作。所以我有我的 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 做事方式。但是我需要检查启动时数据库是否存在。所以我想在 Application类 事件侦听器中检查 ApplicationReadyEvent。但是我如何获得对数据源 url 的引用?我之前有一个配置 属性 并自动加载,我仍然可以这样做,但它会在某些地方,那会很糟糕。

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

您可以使用 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";
        }
    }

}