H2是一个Java编写的关系型数据库,它可以被嵌入Java应用程序中使用,或者作为一个单独的数据库服务器运行。
简介
H2数据库是一个非常小巧的关系数据库。我最初接触H2数据库是在一个叫nginxWebUI的开源项目中,该项目直接部署使用,并不需要安装数据库,初始化数据表等操作。它内置了一个H2数据库,在系统运行初始化过程中会根据应用程序配置自动初始化数据库表。而在业务处理中的数据库操作和通用的关系数据库差距不大。
我个人认为可以用作一些数据量不大的个人项目使用。如一些配置工具;也可用作一些C/S架构的客户端数据存储等;
以下是我们在项目中如何使用H2数据库的基本步骤:
使用步骤
1、首先我根据springboot初始化了一个简单的项目
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.0</version> <relativePath/> <!-- lookup parent from repository --></parent>
2、添加了H2数据库的maven坐标
<!-- H2数据库配置 --><dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId></dependency><!-- 通过mybatis操作数据库 --><dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.2</version></dependency>
3、application.yaml文件中关于H2数据库的配置
spring: sql: init: platform: h2 schema-locations: classpath:db/schema-h2.sql mode: always datasource: driverClassName: org.h2.Driver url: jdbc:h2:./data/xxx;AUTO_SERVER=TRUE username: sa password: 123456 h2: console: enabled: true path: /h2console settings: web-allow-others: true
其中:
spring.sql.init.schema-location:
classpath:db/schema-h2.sql文件为数据的初始化sql语句,我主要放了一些建表语句,在系统第一次启动时生效;
spring.datasource.url为jdbc:h2:./data/xxx;AUTO_SERVER=TRUE其中./data/xxx为产生数据库的文件路径,系统启动过程中会在该位置生成数据库文件;
spring.h2.path为对外输出的控制台信息
4、当系统启动后可通过控制台查看数据库的创建信息;

5、后续过程就正常使用mybatis操作数据库即可。