【发布时间】:2018-12-21 20:14:55
【问题描述】:
我正在为我的数据库使用 Spring Boot、H2 和 JPA,我可以通过将我的连接属性放入 application.properties 来连接到数据库。但我不知道如何使用 Spring Boot 为我建立的连接。
在下面的代码中,我可以使用conn 来运行语句等。
static final String JDBC_DRIVER = "org.h2.Driver";
static final String DB_URL = "jdbc:h2:~/test";
static final String USER = "sa";
static final String PASS = "";
Connection conn = null;
Statement stmt = null;
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//This is what I want to do with spring as I obtain a conn variable and use it.
stmt = conn.createStatement();
String sql = "CREATE TABLE REGISTRATION " +
"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))";
stmt.executeUpdate(sql);
stmt.close();
conn.close();
application.properties
spring.datasource.url=jdbc:h2:mem:example-
app;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.platform=h2
spring.datasource.username = sa
spring.datasource.password =
spring.datasource.driverClassName = org.h2.Driver
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.h2.console.path=/console
【问题讨论】:
标签: java spring-boot jdbc h2 spring-jdbc