【发布时间】:2015-12-28 19:06:20
【问题描述】:
我的小型 Spring Boot 应用程序在 src/main/resources 下有此配置:
server.port = 8090
spring.datasource.driverClassName = org.h2.Driver
spring.datasource.url = jdbc:h2:file:~/stapler
我知道这个配置是正确的,因为应用程序启动日志中有有效的端口号 8090。还有一个 @PostConstruct initDb() 方法可以创建数据并将其插入到该数据库的 2 个表中:
package com.avk.stapler.init;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.annotation.PostConstruct;
@SpringBootApplication
public class DbInitializer {
@Autowired
private JdbcTemplate jdbcTemplate;
public static void main(String[] args) {
SpringApplication.run(DbInitializer.class, args);
}
@PostConstruct
private void initDb() {
System.out.println("Creating table employees");
jdbcTemplate.execute("drop table employees if exists");
jdbcTemplate.execute("create table employees(id serial, name varchar(255), surname varchar(255))");
jdbcTemplate.execute("insert into employees(name, surname) values('Jan', 'Kowalski')");
jdbcTemplate.execute("insert into employees(name, surname) values('Stefan', 'Nowak')");
System.out.println("Creating table allocations");
jdbcTemplate.execute("drop table allocations if exists");
jdbcTemplate.execute("create table allocations(id serial, week int, year int, shift int, employee_id bigint)");
jdbcTemplate.execute("insert into allocations(week, year, shift, employee_id) values(29, 2015, 1, 1)");
jdbcTemplate.execute("insert into allocations(week, year, shift, employee_id) values(28, 2015, 2, 1)");
jdbcTemplate.execute("insert into allocations(week, year, shift, employee_id) values(29, 2015, 3, 2)");
jdbcTemplate.execute("insert into allocations(week, year, shift, employee_id) values(28, 2015, 2, 2)");
}
}
我可以在启动时看到这个记录,我认为没有更多关于 DB 的日志:
2015-09-30 22:41:22.948 INFO 2832 --- [ main] o.s.j.d.e.EmbeddedDatabaseFactory : Creating embedded database 'testdb'
Creating table employees
Creating table allocations
由于上述原因,我希望在我的主目录中看到一个“stapler.h2.db”文件,但事实并非如此。此处应更改哪些内容才能显示 DB 文件?
【问题讨论】:
-
只是一个疯狂的猜测:你确定数据库不只在内存中吗? h2database.com/html/features.html#in_memory_databases
-
内存中只是 H2 支持的模式之一,我相信。我之前肯定在我的驱动器上看到过 *.h2.db 文件。
-
我并不是暗示 H2 仅在内存中,而是您可能正在运行它......
标签: java spring-boot spring-data h2