Spring Boot H2 简明教程
Spring Boot & H2 - Overview
What is H2?
H2 数据库是一个开源、嵌入式且内存驻留的关系数据库管理系统。它使用 Java 编写,提供一个客户端/服务器应用程序。它将数据存储在系统内存中,而不是磁盘。一旦程序关闭,数据也会丢失。当我们不想保留数据以及单元测试整体功能时,可以使用内存数据库。其他一些流行的内存数据库包括 HSQLDB 或 HyperSQL 数据库以及 Apache Derby。H2 是其他嵌入式数据库中最流行的数据库。
H2 database is an open source, embedded and in memory relational database management system. It is written in Java and provides a client/server application. It stores data in system memory instead of disk. Once program is closed, data is also lost. An in memory database is used when we don’t want to persist the data and unit test the overall functionality. Some of the other popular in memory databases are HSQLDB or HyperSQL Database and Apache Derby. H2 is the most popular one among other embedded databases.
Advantages of H2 Database
以下是 H2 提供的优势列表 -
Following is the list of advantages that H2 provides −
-
No configuration − Spring Boot intrinsically supports H2 and no extra configuration required to configure H2 database.
-
Easy to Use − H2 Database is very easy to use.
-
Lightweight and Fast − H2 database is very lightweight and being in memory, it is very fast.
-
Switch configurations − Using profiles, you can easily switch between production level database and in-memory database.
-
Supports Standard SQL and JDBC − H2 database supports almost all the features of Standard SQL and operations of JDBC.
-
Web Based Console − H2 Database can be managed by its web based console application.
Configuring H2 Database
将 H2 数据库添加为 maven 依赖项,就是这样。
Add H2 Database as maven dependency and that’s it.
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
尽管 Spring Boot 会自动配置 H2 数据库。我们可以在 application.properties 中指定它们来覆盖默认配置,如下所示。
Although, spring boot configures H2 database automatically. We can override the default configurations by specifying them in application.properties as shown below.
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true