在Spring Boot使用H2內存數據庫
在之前的文章中我們有提到在Spring Boot中使用H2內存數據庫方便開發和測試。本文我們將會提供一些更加具體有用的信息來方便我們使用H2數據庫。
添加依賴配置
要想使用H2,我們需要添加如下配置:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
數據庫配置
有了上面的依賴,默認情況下Spring Boot會為我們自動創建內存H2數據庫,方便我們使用,當然我們也可以使用自己的配置,我們將配置寫入application.properties:
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
默認情況下內存數據庫會在程序結束之后被銷毀,如果我們想永久保存內存數據庫需要添加如下配置:
spring.datasource.url=jdbc:h2:file:/data/demo
這里配置的是數據庫的文件存儲地址。
添加初始數據
我們可以在resources文件中添加data.sql 文件,用來在程序啟動時,創建所需的數據庫:
DROP TABLE IF EXISTS billionaires;
CREATE TABLE billionaires (
id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(250) NOT NULL,
last_name VARCHAR(250) NOT NULL,
career VARCHAR(250) DEFAULT NULL
);
INSERT INTO billionaires (first_name, last_name, career) VALUES
('Aliko', 'Dangote', 'Billionaire Industrialist'),
('Bill', 'Gates', 'Billionaire Tech Entrepreneur'),
('Folrunsho', 'Alakija', 'Billionaire Oil Magnate');
Spring Boot在啟動時候會自動加載data.sql文件。這種方式非常方便我們用來測試。
訪問H2數據庫
雖然是一個內存數據庫,我們也可以在外部訪問和管理H2,H2提供了一個內嵌的GUI管理程序,我們看下怎么使用。首先需要添加如下權限:
spring.h2.console.enabled=true
啟動程序, 我們訪問 http://localhost:8080/h2-console ,得到如下界面:
記得填入你在配置文件中配置的地址和密碼。
登錄之后,我們可以看到如下的管理界面:
我們還可以添加如下配置來管理這個GUI:
spring.h2.console.path=/h2-console
spring.h2.console.settings.trace=false
spring.h2.console.settings.web-allow-others=false
其中path指定了路徑,trace指定是否開啟trace output,web-allow-others指定是否允許遠程登錄。
本文的例子可以參考https://github.com/ddean2009/learn-springboot2/tree/master/springboot-h2