h2数据库有2中模型,一种是嵌入式,一种是服务端。嵌入式时,我们多个配置同一个地址就可以访问同一个数据集,服务端需要额外开启服务,再通过ip端口访问。这里我们介绍下怎么在springboot项目下开启服务端模式。

1、在springboot应准备就绪后启动h2服务

public class H2Server implements ApplicationListener<ApplicationPreparedEvent> {
	@Override
	public void onApplicationEvent(ApplicationPreparedEvent event) {
		String[] args = new String[] { "-tcpPort", "9007", "-tcpPassword", "abc123", "-tcpAllowOthers", "-ifNotExists" };
		log.info("准备启动H2数据库,启动参数:{}", JSON.toJSONString(args));
		try {
			Server h2Server = Server.createTcpServer(args).start();
			if (h2Server.isRunning(true)) {
				log.info("H2数据库启动成功,地址:{},端口:{}", h2Server.getURL(), h2Server.getPort());
			}
		} catch (SQLException e) {
			log.error("H2数据库启动出错", e);
		}
	}
}

参数说明:

-tcpPort:服务端口

-tcpPassword:服务密码

-tcpAllowOthers:运行其他主机访问

 

2、启动类添加创建好的监听

public class EbiCheckApplication {
	public static void main(String[] args) {
		SpringApplication app = new SpringApplicationBuilder(H2TestApplication.class).bannerMode(Mode.OFF).build();
		app.addListeners(new H2Server());
		app.run(args);
	}
}

 

3、pom.xml中添加驱动

<dependency>
	<groupId>com.h2database</groupId>
	<artifactId>h2</artifactId>
</dependency>

 

4、 配置数据源参数

spring.datasource.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:tcp://localhost:9007/./h2_test
spring.datasource.username=root
spring.datasource.password=abc123
spring.datasource.type=org.apache.commons.dbcp2.BasicDataSource

服务启动后就是在springboot应用当前目录创建h2_test.mv.db文件,这就是我们的数据库文件了。也可以配置成~/h2_test,这样就会在用户目录下创建数据库文件

 

5、dbeaver配置连接

posted on 2023-05-29 14:43  玄同太子  阅读(193)  评论(0编辑  收藏  举报