嵌入式SQLite結合SpringBoot快速建構開發環境

最近在開發微服務,想套用簡單的DB架構,不受限於DB環境
因此引入了SQLite這個Embedded DB技術,結合Spring Boot,很快就能上手!

Embedded DB 簡介

在查找Embedded DB時,有使用過Derby和SQLite兩種
簡易比較如下表

名稱優點缺點
Derby* JDK內建,無須額外lib* Table大量資料時執行效能明顯下降
* 同時只能有單一執行緒連入
SQLite* 執行效能較佳
* 支援多執行緒同時連入
* DB儲存檔為單一檔案
* 不支援DateTime資料型態(要用string或long替代)

我自己歸納了一下適用Embedded DB的情境:
  • DB內容固定的微服務
  • 研發初期尚未決定使用的DB
  • 做執行log搜集
  • 做為unit test dao類的datasource,搭配dbunit架構執行測試
  • 開發人員自己嘗試新功能/技術研發


Spring Boot + SQLite設定

使用spring boot 2.0.5版本,maven設定繼承spring-boot-starter-parent
<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.0.5.RELEASE</version>
</parent>

加入會用到的spring lib
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-test</artifactId>
 <scope>test</scope>
</dependency>
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

加入SQLite driver lib
<dependency>
 <groupId>org.xerial</groupId>
 <artifactId>sqlite-jdbc</artifactId>
</dependency>

使用github上寫好的dialect
<dependency>
 <groupId>com.github.gwenn</groupId>
 <artifactId>sqlite-dialect</artifactId>
 <version>0.1.0</version>
</dependency>

增加application.properties的設定
spring.datasource.url = jdbc:sqlite:pbm.db   <-- 指向專案根目錄,產生一個pbm.db的檔案
spring.datasource.driver-class-name = org.sqlite.JDBC
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.SQLiteDialect
spring.jpa.hibernate.ddl-auto=none     <-- Embedded DB預設是create-drop,資料每次都會被砍掉,改成none不做任何處理
spring.jpa.show-sql=true
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

上述設定,也可使用application.yml的方式來設定
執行spring boot程式(在eclipse要用springboot啟動的方式來執行,才會吃到設定),就會自動產生sqlite的pbm.db檔案囉!
sql操作SQL可參考:Java使用JDBC操作SQLite

補充說明:
日期時間欄位,在sqlite裡是用文字存,但操作時用DateTime格式是ok的
不過在自行塞入日期時間資料時,發現程式會抓不到自己塞的資料,然而單元測試卻又能正常抓到。
後來發現在單元測試save進去的日期時間是會變成數字格式的內容,但sql是能正常select得到,
所以若有須要自行準備資料時,得從單元測試塞一筆data看其對應的數字做為該日期時間欄位的值。

留言

這個網誌中的熱門文章