原創(chuàng)文章, 轉(zhuǎn)載請注明出處
博客鏈接地址
在日常開發(fā)過程中,特別是敏捷開發(fā)過程以及測試過程中,我們有時候不想操縱真實的數(shù)據(jù)庫.那么,H2數(shù)據(jù)庫是個不錯的選擇。
H2是一個開源的、純java實現(xiàn)的關(guān)系數(shù)據(jù)庫。
h2數(shù)據(jù)庫特點
(1)性能、小巧
(2)同時支持網(wǎng)絡(luò)版和嵌入式版本,另外還提供了內(nèi)存版
(3)有比較好的兼容性,支持相當(dāng)標(biāo)準(zhǔn)的sql標(biāo)準(zhǔn)
(4)提供了非常友好的基于web的數(shù)據(jù)庫管理界面
在spring boot項目中配置H2數(shù)據(jù)庫
application.properies
spring.datasource.url=jdbc:h2:mem:test_db
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.schema=classpath:db/schema.sql
spring.datasource.data=classpath:db/data.sql
spring.h2.console.enabled=true
- spring.datasource.url=jdbc:h2:mem:test,配置h2數(shù)據(jù)庫的連接地址
- spring.datasource.driver-class-name=org.h2.Driver,配置JDBC Driver
- spring.datasource.username=root,配置數(shù)據(jù)庫用戶名
- spring.datasource.password=,配置數(shù)據(jù)庫密碼
- spring.datasource.schema=classpath:db/schema.sql,進(jìn)行該配置后,每次啟動程序,程序都會運行resources/db/schema.sql文件,對數(shù)據(jù)庫的結(jié)構(gòu)進(jìn)行操作。
- spring.datasource.data=classpath:db/data.sql,進(jìn)行該配置后,每次啟動程序,程序都會運行resources/db/data.sql文件,對數(shù)據(jù)庫的數(shù)據(jù)操作
- spring.h2.console.enabled=true,開啟web console功能
schema.sql
CREATE TABLE student(
id int not null,
name varchar(20) null,
age int null
);
data.sql
INSERT INTO student VALUES (1,'張三',10);
INSERT INTO student VALUES (2,'李四',16);
項目目錄結(jié)構(gòu)變?yōu)槿缦?

1.png
配置完成后,啟動項目后,瀏覽器中輸入http://localhost:8080/h2-console/

2.png
登錄后頁面為:

3.png
項目代碼地址: https://github.com/felix1982/spring-boot-practice/tree/master/spring-boot-h2