代码之家  ›  专栏  ›  技术社区  ›  mmaceachran

检查h2 db文件是否存在

  •  0
  • mmaceachran  · 技术社区  · 5 年前

    我在一个文件上使用了一个真正简单的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...
    }
    

    但我现在正试图用一种“正确”的弹簧引导方式来实现这一点。因此,我的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的引用?我以前有一个配置属性,并被自动加载,我仍然可以这样做,但它将在个位置,这将是很糟糕的。

    那么,当应用程序启动时,确保数据库文件存在的散文家/正确方法是什么呢?(我想用JDBC的方式,不要用JPA)

    1 回复  |  直到 5 年前
        1
  •  3
  •   user10639668    5 年前

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