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