在Spring Boot使用H2內存數據庫

在Spring Boot使用H2內存數據庫git

在以前的文章中咱們有提到在Spring Boot中使用H2內存數據庫方便開發和測試。本文咱們將會提供一些更加具體有用的信息來方便咱們使用H2數據庫。github

添加依賴配置

要想使用H2,咱們須要添加以下配置:web

<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

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

默認狀況下內存數據庫會在程序結束以後被銷燬,若是咱們想永久保存內存數據庫須要添加以下配置:sql

spring.datasource.url=jdbc:h2:file:/data/demo

這裏配置的是數據庫的文件存儲地址。數據庫

添加初始數據

咱們能夠在resources文件中添加data.sql 文件,用來在程序啓動時,建立所需的數據庫:springboot

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文件。這種方式很是方便咱們用來測試。app

訪問H2數據庫

雖然是一個內存數據庫,咱們也能夠在外部訪問和管理H2,H2提供了一個內嵌的GUI管理程序,咱們看下怎麼使用。首先須要添加以下權限:spring-boot

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

更多內容請參考 http://www.flydean.com/spring-boot-h2/

相關文章
相關標籤/搜索