H2
是一个用Java
编写的数据库,类似tomcat
,有自己的安装包,同时又提供了内嵌功能,只需要引入相关jar包即可.
既然是内嵌的,那么它的生命周期与当前服务保持一致,即服务启动时开启(并初始化),服务停止后数据消失,正是由于这样的特性,所以特别适合用来做测试.
本文采用Springboot+Spring Jpa + h2
做演示.
依赖
关键依赖如下,其他请参考源码
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
application.yaml
spring:
datasource:
platform: h2
username: sa # 默认用户名
password: sa # 默认为空
# 此处只展示内存模式,更多请参考http://www.h2database.com/html/features.html#database_url
url: jdbc:h2:mem:dbtest
driver-class-name: org.h2.Driver
# 一定要加classpath前缀,否则无法初始化
schema: classpath*:h2/schema.sql
data: classpath*:h2/data.sql
# initialization-mode: always
jpa:
show-sql: true
h2:
console:
# 是否开启h2控制台
enabled: true
settings:
# 是否允许远程访问console
web-allow-others: true
# 默认为/h2-console,生效前提是${spring.h2.console}=true,表示访问此URI进入H2控制台
path: /h2
mybatis:
mapper-locations: classpath*:mapper/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
业务逻辑代码与MyBatis配置
参考源码
问题
-
一开始总是无法初始化
H2
,后来找到原因:spring.datasource.schema
和spring.datasource.data
的路径中一定要加classpath
前缀!!! -
添加用户时入参总为空
UserController#addUser
参数定义处未添加注解@RequestBody
.