spring boot集成h2指南

依賴

添加依賴文件。若是你使用的是gradle,則能夠在build.gradle文件種加入下面代碼php

dependencies {
    compile 'com.h2database:h2:1.4.192'
}

鏈接配置

application.properties,文件中對數據庫,進行鏈接配置html

  • spring.datasource.url=jdbc:h2:mem:test,配置h2數據庫的鏈接地址web

  • spring.datasource.driver-class-name=org.h2.Driver,配置JDBC Driverspring

  • spring.datasource.username=root,配置數據庫用戶名sql

  • spring.datasource.password=123456,配置數據庫密碼數據庫

當你完成依賴鏈接配置這兩步以後,你就能夠在程序種使用h2了。spring會自動幫你完成DataSource的注入,以後不管你是用JPA仍是MyBatis,或者別的框架就隨你了。app

數據初始化配置

若是你須要在程序啓動時對數據庫進行初始化操做,則在application.properties文件中對數據庫進接配置框架

  • spring.datasource.schema=classpath:db/schema.sql,進行該配置後,每次啓動程序,程序都會運行resources/db/schema.sql文件,對數據庫的結構進行操做。spring-boot

  • spring.datasource.data=classpath:db/data.sql,進行該配置後,每次啓動程序,程序都會運行resources/db/data.sql文件,對數據庫的數據操做。測試

該配置很是適合開發環境,我會把數據庫的結構構建sql放在resources/db/schema.sql,數據sql放在resources/db/data.sql中。這樣每次運行程序我均可以獲得一個新的數據庫。這樣就不須要我每次爲了測試而修改數據中的內容了。

h2 web consloe配置

h2 web consloe是一個數據庫GUI管理應用,就和phpMyAdmin相似。程序運行時,會自動啓動h2 web consloe。固然你也能夠進行以下的配置。

  • spring.h2.console.settings.web-allow-others=true,進行該配置後,h2 web consloe就能夠在遠程訪問了。不然只能在本機訪問。

  • spring.h2.console.path=/h2-console,進行該配置,你就能夠經過YOUR_URL/h2-console訪問h2 web consloeYOUR_URL是你程序的訪問URl。

  • spring.h2.console.enabled=true,進行該配置,程序開啓時就會啓動h2 web consloe。固然這是默認的,若是你不想在啓動程序時啓動h2 web consloe,那麼就設置爲false

參考

Using H2’s web console
Connection to a production database
Initialize a database using Spring JDBC

相關文章
相關標籤/搜索