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

  1. 配置spring.h2.console.enabled=true
  2. 依赖Spring MVC (spring-cloud-starter-gateway使用WebFlux,而不是Spring MVC,默认无法访问h2-console)
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐