h2是一種內存數(shù)據(jù)庫,可以方便的整合進spring-boot項目內。
1. application.properties
#配置數(shù)據(jù)庫連接地址
spring.datasource.primary.jdbc-url=jdbc:h2:file:./h2/code-generator;AUTO_SERVER=TRUE;DB_CLOSE_ON_EXIT=FALSE
#配置數(shù)據(jù)庫驅動
spring.datasource.primary.driver-class-name=org.h2.Driver
#配置數(shù)據(jù)庫用戶名
spring.datasource.primary.username=root
#配置數(shù)據(jù)庫密碼
spring.datasource.primary.password=root
#配置能遠程訪問
spring.h2.console.settings.web-allow-others=true
#配置訪問地址
spring.h2.console.path=/h2-console
#配置項目啟動 h2就啟動
spring.h2.console.enabled=true
jbdc-url的配置:
- file:./h2/code-generator; 表示在項目根路徑下保存數(shù)據(jù)庫文件,數(shù)據(jù)庫的名稱為code-generator,
- AUTO_SERVER=true 啟動自動混合模式,允許開啟多個連接,該參數(shù)不支持在內存中運行模式
- DB_CLOSE_ON_EXIT 當虛擬機退出時并不關閉數(shù)據(jù)庫
2. h2控制臺
訪問http://localhost:8089/h2-console,頁面如下圖

image.png
其中JDBC URL輸入框內輸入配置文件內jdbc-url的前半部分,User Name和Password是我們配置文件內配置的username和password。進入后就可以看到我們的數(shù)據(jù)庫code-generator和它下面的表了。
需要注意的是如果按照官方示例:jpa-multiple-datasources內的方式配置內存數(shù)據(jù)庫,如下
return new EmbeddedDatabaseBuilder().//
setType(EmbeddedDatabaseType.H2).//
setName("customers").//
build();
等價于
spring.datasource.primary.jdbc-url=jdbc:h2:mem:customers;
spring.datasource.primary.username=sa
spring.datasource.primary.password=
- jdbc:h2:file:E:/data/H2 表示將初始化的數(shù)據(jù)和H2 Console控制臺執(zhí)行的數(shù)據(jù)保存到E盤下data/H2文件夾中,即使應用重啟,數(shù)據(jù)不會丟失。
- jdbc:h2:/testdatabase這里就需要說明一下””這個符號在window操作系統(tǒng)下代表什么意思了,在Window操作系統(tǒng)下,”~”這個符號代表的就是當前登錄到操作系統(tǒng)的用戶對應的用戶目錄,所以testdatabase數(shù)據(jù)庫對應的文件存放在登錄到操作系統(tǒng)的用戶對應的用戶目錄當中,比如我當前是使用Administrator用戶登錄操作系統(tǒng)的,所以在”C:\Documents and Settings\Administrator.h2”目錄中就可以找到test數(shù)據(jù)庫對應的數(shù)據(jù)庫文件了
持久化本地的問題:由于本地已經(jīng)存在表,而應用每次啟動都會創(chuàng)建表,導致下次啟動時會啟動報錯。除非手動注掉application.properties中新建表的配置,或則刪除本地對應目錄的文件。
3.jdbc:h2:mem:soa_service_api、jdbc:h2:mem:~/.h2/url類似與這種配置的,表示將初始化和h2 console控制臺上操作的數(shù)據(jù)保存在內存(mem-memory)
保存到內存的問題:由于每次重啟應用內存釋放掉后,對應的數(shù)據(jù)也會消失,當然初始化的表+初始化數(shù)據(jù)就都沒了。然后重啟會從data.sql中重新初始化數(shù)據(jù),啟動正常。但是你通過h2