您可以将 H2 服务器设置为 Spring Bean。
首先编辑 pom.xml - 从 h2 依赖中删除 <scope>runtime</scope>:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
然后将H2服务器bean添加到SpringBootApplication或Configuration类:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
/**
* Start internal H2 server so we can query the DB from IDE
*
* @return H2 Server instance
* @throws SQLException
*/
@Bean(initMethod = "start", destroyMethod = "stop")
public Server h2Server() throws SQLException {
return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9092");
}
}
最后 - 编辑application.properties - 设置数据库名称:
spring.datasource.url=jdbc:h2:mem:dbname
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create
然后您可以使用此连接从外部连接到此 H2 服务器(例如,使用 H2 DB 连接到您的应用程序):
jdbc:h2:tcp://localhost:9092/mem:dbname
使用此网址作为奖励,您可以直接从您的 IDE 连接到应用程序的数据库。
更新
尝试连接到 H2 for Spring Boot app 1.5.x 版本时可能会出错。在这种情况下,只需将 H2 的版本更改为以前的版本,例如:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.193</version>
</dependency>
更新 2
如果您需要在同一主机上同时运行多个带有 H2 的应用程序,您应该在 Server.createTcpServer 方法中为它们设置不同的 H2 端口,例如:9092、9093 等。
// First App
@Bean(initMethod = "start", destroyMethod = "stop")
public Server h2Server() throws SQLException {
return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9092");
}
// Second App
@Bean(initMethod = "start", destroyMethod = "stop")
public Server h2Server() throws SQLException {
return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9093");
}
然后您可以使用以下 url 连接到这些应用程序的 H2 DB:
App1 H2: jdbc:h2:tcp://localhost:9092/mem:dbname
App2 H2: jdbc:h2:tcp://localhost:9093/mem:dbname