H2 Database

h2支持运行三种模式

  • Embedded (嵌入式) : 无需配置本地(或远程)数据库 ; 数据库连接关闭时,数据与表结构依然存在;

  • In-Memory (内存模式): 同上,区别:数据库连接关闭时,数据与表结构删除;

  • ServerMode(传统模式) : 需要配置本地(或远程)数据库;

  • 内存模式的数据库URL

  jdbc:h2:mem:
jdbc:h2:mem:<databaseName>
jdbc:h2:mem:test_mem
jdbc:h2:tcp://localhost/mem:db1
  • 嵌入模式的URL
  jdbc:h2:[file:][<path>]<databaseName>
jdbc:h2:~/test
jdbc:h2:file:/data/sample
jdbc:h2:file:C:/data/sample (Windows only)
  • server模式
  jdbc:h2:tcp://<server>[:<port>]/[<path>]<databaseName>
jdbc:h2:tcp://localhost/~/test
jdbc:h2:tcp://dbserv:8084/~/sample
jdbc:h2:tcp://localhost/mem:test
jdbc:h2:ssl://<server>[:<port>]/[<path>]<databaseName>
jdbc:h2:ssl://localhost:8085/~/sample;

Spring Boot集成H2数据库

添加依赖

        <dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>

配置application.yml

# DataSource Config
spring:
datasource:
driver-class-name: org.h2.Driver
schema: classpath:db/schema.sql #,每次启动程序,程序都会运行schema.sql文件,对数据库的数据操作
data: classpath:db/data.sql #,每次启动程序,程序都会运行data.sql文件,对数据库的数据操作
url: jdbc:h2:mem:test #配置h2数据库的连接地址
username: sa
password: sa
h2:
console:
enabled: true #开启web console功能

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@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');

启动项目后,浏览器中输入http://localhost:8080/h2-console/

Spring Boot + Mybatis + H2 database数据库-LMLPHP

登录后页面:

Spring Boot + Mybatis + H2 database数据库-LMLPHP

User.java

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

UserDao .java

@Repository
@Mapper
public interface UserDao { @Select("select * from user where id= #{id}")
User findById(Integer id);
}
@SpringBootApplication
public class MybatisApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(MybatisApplication.class, args);
} @Resource
private UserMapper userMapper; @Override
public void run(String... args) throws Exception {
System.out.println(userMapper.selectById(100L));
}
}
05-07 15:11
查看更多