原創作品,可以轉載,但是請標注出處地址:https://www.cnblogs.com/V1haoge/p/9959855.html
SpringBoot整合H2內存數據庫
一般我們在測試的時候習慣於使用內存內存數據庫,這里我們整合h2數據庫。
步驟
第一步:添加必要的jar包
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
還可以添加一些額外的工具jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
前者是必備jar包,后者是輔助jar包,用於查看內存數據庫。
第二步:添加必要的配置
#h2配置
spring.jpa.show-sql = true #啟用SQL語句的日志記錄
spring.jpa.hibernate.ddl-auto = update #設置ddl模式
##數據庫連接設置
spring.datasource.url = jdbc:h2:mem:dbtest #配置h2數據庫的連接地址
spring.datasource.username = sa #配置數據庫用戶名
spring.datasource.password = sa #配置數據庫密碼
spring.datasource.driverClassName =org.h2.Driver #配置JDBC Driver
##數據初始化設置
spring.datasource.schema=classpath:db/schema.sql #進行該配置后,每次啟動程序,程序都會運行resources/db/schema.sql文件,對數據庫的結構進行操作。
spring.datasource.data=classpath:db/data.sql #進行該配置后,每次啟動程序,程序都會運行resources/db/data.sql文件,對數據庫的數據操作。
##h2 web console設置
spring.datasource.platform=h2 #表明使用的數據庫平台是h2
spring.h2.console.settings.web-allow-others=true # 進行該配置后,h2 web consloe就可以在遠程訪問了。否則只能在本機訪問。
spring.h2.console.path=/h2 #進行該配置,你就可以通過YOUR_URL/h2訪問h2 web consloe。YOUR_URL是你程序的訪問URl。
spring.h2.console.enabled=true #進行該配置,程序開啟時就會啟動h2 web consloe。當然這是默認的,如果你不想在啟動程序時啟動h2 web consloe,那么就設置為false。
第三步:添加數據庫結構與數據腳本
resources/db/schema.sql
create table if not exists USER (
USE_ID int not null primary key auto_increment,
USE_NAME varchar(100),
USE_SEX varchar(1),
USE_AGE NUMBER(3),
USE_ID_NO VARCHAR(18),
USE_PHONE_NUM VARCHAR(11),
USE_EMAIL VARCHAR(100),
CREATE_TIME DATE,
MODIFY_TIME DATE,
USE_STATE VARCHAR(1));
resourses/db/data.sql
INSERT INTO USER (USE_ID,USE_NAME,USE_SEX,USE_AGE,USE_ID_NO,USE_PHONE_NUM,USE_EMAIL,CREATE_TIME,MODIFY_TIME,USE_STATE) VALUES(
1,'趙一','0',20,'142323198610051234','12345678910','qe259@163.com',sysdate,sysdate,'0');
INSERT INTO USER (USE_ID,USE_NAME,USE_SEX,USE_AGE,USE_ID_NO,USE_PHONE_NUM,USE_EMAIL,CREATE_TIME,MODIFY_TIME,USE_STATE) VALUES(
2,'錢二','0',22,'142323198610051235','12345678911','qe259@164.com',sysdate,sysdate,'0');
INSERT INTO USER (USE_ID,USE_NAME,USE_SEX,USE_AGE,USE_ID_NO,USE_PHONE_NUM,USE_EMAIL,CREATE_TIME,MODIFY_TIME,USE_STATE) VALUES(
3,'孫三','1',24,'142323198610051236','12345678912','qe259@165.com',sysdate,sysdate,'0');
第四步:查看h2-console
瀏覽器輸入:
http://localhost:8080/h2
可以打開h2數據庫管理器登錄界面:
輸入配置的數據庫信息,點擊登錄,即可打開操作界面: