springboot集成h2数据库

30 篇文章 2 订阅
12 篇文章 1 订阅

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

  1. 配置spring.h2.console.enabled=true
  2. 依赖Spring MVC (spring-cloud-starter-gateway使用WebFlux,而不是Spring MVC,默认无法访问h2-console)
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

搬山境KL攻城狮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值