1. 概述
- 在 Spring 开发中, 引入 H2 做辅助测试数据库
2. 场景
- 复习 Spring, 复习到 持久化 部分
- 需要一个 数据库 来做测试
- 方案
- 方案1: 搭建 MySQL 实例
- 虽然现在有 docker 环境, 但我还是懒得弄
- 真的懒...
- 方案2: 使用 H2 数据库
- 使用 embedded 版本
- 可以使用 内存数据库
- 随用随启
- 数据每次都是新的
- 嗯, 决定就是它了
- 思路
- H2 的使用, 也特别简单
- maven 添加好依赖
- 简单配置
- 启动项目
- 验证启动即可
3. 环境
- os
- win10
- jdk
- 1.8
- ide
- ida 2018.1
- spring
- spring boot
- 2.1.7 release
- 组件
- thymeleaf
- starter-web
- devtool
- starter-test
- browser
- firefox
- 70.0
- H2
- 1.4.197
- ref
- spring in action 5th
4. 步骤们
1. 引入依赖
- 概述
- 在 pom 文件里引入依赖
代码如下
<!-- JdbcTemplate -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- h2 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
- 解释
- 引入 JdbcTemplate
- 与 H2 交互的时候, 真的需要驱动
- 引入 H2
- 使用数据库
- 注意
- 引入后一定要确保 lib 下下来
- 我没有确认, 然后傻等了好久
- 都开始找 bug 了
2. 配置
- 概述
- H2 数据库的启动, 打开 web console
- 因为启动在 spring 的同个 jvm 里, 不太好确认
- 可以通过 run > endpoint > health 下看到 有个 db
配置文件
# dataSource: H2
## H2: 开启 console
### 开启 console
spring.h2.console.enabled=true
### 设定 console 路径
spring.h2.console.path=/console
3. 验证
重启项目
打开浏览器, 进入 console
# 如果能打开, 说明启动成功了
localhost:8080/console
ps
- ref
- Spring Boot – Spring Data JPA with Hibernate and H2 Web Console
- 这里用的是 jpa 配合 hibernate 的方案, 可以看看
- 问题
- 我们要测试的数据, 如何写入
- 我们写入后, 如何通过这个 console 查看
- 这些问题, 我会在后面的博客里继续说明
Spring - 周边设施 - H2 embedded 版本引入
原文:https://www.cnblogs.com/xy14/p/11759240.html