springboot集成h2数据库
1. pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
2. application.yml
- before springboot 2.5.0
org.springframework.boot.autoconfigure.jdbc.DataSourceProperties
server:
port: 8080
spring:
datasource:
driver-class-name: org.h2.Driver
# 内存、用户目录、工作目录
url: jdbc:h2:mem:test
# url: jdbc:h2:file:~/db/test
# url: jdbc:h2:file:./test
username: root
password: test
schema:
- classpath:db/schema.sql
data:
- classpath:db/data.sql
h2:
console:
enabled: true
path: /h2-console
settings:
trace: true
web-allow-others: true
- since springboot 2.5.0
org.springframework.boot.autoconfigure.sql.init.SqlInitializationProperties
server:
port: 8080
spring:
datasource:
driver-class-name: org.h2.Driver
# 内存、用户目录、工作目录
url: jdbc:h2:mem:test
# url: jdbc:h2:file:~/db/test
# url: jdbc:h2:file:./test
username: root
password: test
sql:
init:
schema-locations: classpath:db/schema.sql
data-locations: classpath:db/data.sql
mode: always
h2:
console:
enabled: true
path: /h2-console
settings:
trace: true
web-allow-others: true
3. sql脚本
- schema.sql
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`
(
id BIGINT NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
- data.sql
DELETE FROM `user`;
INSERT INTO `user` (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
4. 访问
http://localhost:8080/h2-console
注意:
org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration
- 配置
spring.h2.console.enabled=true
- 依赖
Spring MVC
(spring-cloud-starter-gateway
使用WebFlux
,而不是Spring MVC
,默认无法访问h2-console
)