配置文件

本文介绍 Spring Boot 集成 H2 数据库基础配置。

application-h2.yml

spring:
  datasource:
    url: jdbc:h2:mem:test
    username: sa
    password: sa
    driver-class-name: org.h2.Driver
    schema:  classpath:db/schema.sql # 表结构
    data: classpath:db/data.sql # 预先准备数据
  h2:
    console:
      enabled: true

数据表

项目路径:resources/db

表结构:schema.sql

DROP TABLE IF EXISTS user;

CREATE TABLE user
(
  id BIGINT(20) NOT NULL COMMENT '主键ID',
  name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
  age INT(11) 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@mangobeta.com'),
  (2, 'Jack', 20, 'test2@mangobeta.com'),
  (3, 'Tom', 28, 'test3@mangobeta.com'),
  (4, 'Sandy', 21, 'test4@mangobeta.com'),
  (5, 'Billie', 24, 'test5@mangobeta.com');

Gradle 配置

build.gradle

compile group: 'com.h2database', name: 'h2', version: '1.4.200'

如果使用 Spring Security,需要添加frame支持

httpSecurity.headers().frameOptions().disable();

访问 h2-console

http://localhost:8081/h2-console

h2-1.png

h2-2.png

测试

User.java

public class User {
private Long id;
private String name;
private Integer age;
private String email;
}

UserDao.java

@Select("select * from user where id= #{id}")
User findById(Integer id);

单测

@SpringBootTest
class UserDaoTest {
    @Autowired
    UserDao userDao;
    



 @Test
void findById() {

       User user = userDao.findById(1);        assertEquals(user.getName(), "Jone");
    }
}

参考: