SpringBoot Database H2

前言

内存数据库(Embedded database或in-momery database)具有配置简单、启动速度快、尤其是其可测试性等优点,使其成为开发过程中非常有用的轻量级数据库。在spring中支持HSQL、H2和Derby三种数据库。H2是Thomas Mueller提供的一个开源的、纯java实现的关系数据库。

各数据库特性对比:

H2 Derby HSQLDB MySQL PostgreSQL
Pure Java Yes Yes Yes No No
Memory Mode Yes Yes Yes No No
Encrypted Database Yes Yes Yes No No
ODBC Driver Yes No No Yes Yes
Fulltext Search Yes No No Yes Yes
Multi Version Concurrency Yes No Yes Yes Yes
Footprint (jar/dll size) ~1 MB ~2 MB ~1 MB ~4 MB ~6 MB

准备

  • JDK 1.8或更高版本
  • Maven 3.5或更高版本

技术栈

  • Spring Data JPA
  • Spring Boot

项目目录结构

项目目录结构

依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.mugwort</groupId>
<artifactId>spring-web</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>spring-web</name>
<description>Demo project for Spring Boot</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<!-- Spring web开发依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 数据库依赖 -->
<!-- h2 嵌入式数据库 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<!-- jpa 依赖,持久化操作依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

实体类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class SystemBean {
private String name;
private String lastaudit;
@Id
@GeneratedValue
@Column(name = "id")
private long id;


public String getLastaudit() {
return lastaudit;
}

public void setLastaudit(String lastaudit) {
this.lastaudit = lastaudit;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}

public String toString() {
return id + " | " + name + " | " + lastaudit;
}
}
  • @Id 声明此属性为主键。该属性值可以通过应该自身创建,但是Hibernate推荐通过Hibernate生成;
  • @GeneratedValue
    指定主键的生成策略。
    • TABLE:使用表保存id值;
    • IDENTITY:identitycolumn;
    • SEQUENCR :sequence;
    • AUTO:根据数据库的不同使用上面三个,默认值;
  • @Column 声明该属性与数据库字段的映射关系。

数据库操作

1
2
3
4

@Repository
public interface SystemRepository extends CrudRepository<SystemBean, Long> {
}

Spring Data JPA包含了一些内置的Repository,实现了一些常用的方法:findone,findall,save等。

应用配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#####
spring.application.name=Bootstrap Spring boot web with H2
### jpa 只进行更新,默认是启动的时候不管三七二十一就删除原来的表结构重新生成
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
#
#显示SQL语句
spring.jpa.show-sql=true
#
# 每次启动程序,程序都会运行resources/db/schema.sql文件,对数据库的结构进行操作。
spring.datasource.schema=classpath:schema.sql
# 每次启动程序,程序都会运行resources/db/data.sql文件,对数据库的数据操作。
spring.datasource.data=classpath:data.sql
#### 驱动类
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#When using database URLs like jdbc:h2:~/test, the database is stored in the user directory. For Windows, this is usually C:\Documents and #Settings\<userName> or C:\Users\<userName>. If the base directory is not set (as in jdbc:h2:./test), the database files are stored in the directory where #the application is started (the current working directory). When using the H2 Console application from the start menu, this is <Installation Directory>/#bin. The base directory can be set in the database URL. A fixed or relative path can be used. When using the URL jdbc:h2:file:./data/sample, the database #is stored in the directory data (relative to the current working directory). The directory is created automatically if it does not yet exist. It is also #possible to use the fully qualified directory name (and for Windows, drive name). Example: jdbc:h2:file:C:/data/test
####===== connect to ======
##这里设置的是数据存储在内存中,也可以存储在磁盘
spring.datasource.url=jdbc:h2:mem:h2test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.name=sa
spring.datasource.password=
spring.datasource.platform=h2
### h2 properties
spring.h2.console.path=/console
spring.h2.console.enabled=true
###### web 访问接口
server.port=8081
### 日志
logging.level.root=info

在application.properties文件中对数据库进行连接配置

spring.datasource.url=jdbc:h2:mem:h2test,配置h2数据库的连接地址
spring.datasource.driver-class-name=org.h2.Driver,配置JDBC Driver
spring.datasource.username=sa,配置数据库用户名
spring.datasource.password=,配置数据库密码

当你完成依赖和连接配置这两步之后,你就可以在程序种使用h2了。spring会自动帮你完成DataSource的注入。

数据初始化配置

如果你需要在程序启动时对数据库进行初始化操作,则在application.properties文件中对数据库进接配置

spring.datasource.schema=classpath:schema.sql,进行该配置后,每次启动程序,程序都会运行resources/schema.sql文件,对数据库的结构进行操作。
spring.datasource.data=classpath:data.sql,进行该配置后,每次启动程序,程序都会运行resources/data.sql文件,对数据库的数据操作。

该配置非常适合开发环境,我会把数据库的结构构建sql放在resources/schema.sql,数据sql放在resources/data.sql中。这样每次运行程序我都可以得到一个新的数据库。这样就不需要我每次为了测试而修改数据中的内容了。
schema.sql代码:

1
2
3
4
5
6
7
DROP  TABLE IF EXISTS  system_bean;
create table system_bean(
id int not null auto_increment,
name varchar(100) not null ,
lastaudit date not null,
primary key (id)
)

data.sql代码:

1
2
3
INSERT INTO system_bean(name,lastaudit)VALUES('Windows Server 2012 R2 ','2017-08-11');
INSERT INTO system_bean(name,lastaudit)VALUES('RHEL 7','2017-07-21');
INSERT INTO system_bean(name,lastaudit)VALUES('Solaris 11','2017-08-13');

h2 web consloe配置

h2 web consloe是一个数据库GUI管理应用,就和phpMyAdmin类似。程序运行时,会自动启动h2 web consloe。当然你也可以进行如下的配置。

spring.h2.console.settings.web-allow-others=true,进行该配置后,h2 web consloe就可以在远程访问了。否则只能在本机访问。
spring.h2.console.path=/h2-console,进行该配置,你就可以通过YOUR_URL/h2-console访问h2 web consloe。YOUR_URL是你程序的访问URl。
spring.h2.console.enabled=true,进行该配置,程序开启时就会启动h2 web consloe。当然这是默认的,如果你不想在启动程序时启动h2 web consloe,那么就设置为false。

参考:
[1]. https://juejin.im/post/5ab4b339f265da238c3a9d0a
[2]. https://412887952-qq-com.iteye.com/blog/2322756