Loading

Springboot 整合 Sqlite

前言:SQLite 是一个软件库,实现了自给自足的、无服务器的、零配置的、事务性的 SQL 数据库引擎。当项目中需要内嵌一个轻量的数据库时,SQLite是一个不错的选择。

1.引入sqlite-jdbc相关的pom依赖

<!-- sqlite -->
<dependency>
    <groupId>org.xerial</groupId>
    <artifactId>sqlite-jdbc</artifactId>
    <version>3.36.0.3</version>
</dependency>

2.用idea等工具创建一个sqlite数据库

  1. idea创建sqlite数据库方法如下:
  2. 将数据库放入指定目录下,如本例中,将数据库文件放置在springboot-sqlite/src/main/resources/db
  3. 添加建表语句db/schema.sql
    -- ----------------------------
    -- Table structure for user
    -- ----------------------------
    DROP TABLE IF EXISTS `user`;
    CREATE TABLE `user`
    (
        `id`     INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        `name`   CHAR(100) NOT NULL,
        `height` REAL      NOT NULL DEFAULT '0',
        `intro`  TEXT               DEFAULT NULL
    );
    
  4. 添加初始数据db/data.sql
    -- ----------------------------
    -- Records of user
    -- ----------------------------
    INSERT INTO `user` (`id`, `name`, `height`, `intro`) VALUES (1, '嘉然', 150.0, '关注嘉然,顿顿接触ovo!');
    INSERT INTO `user` (`id`, `name`, `height`, `intro`) VALUES (2, '向晚', 160.0, '我是向晚!');
    INSERT INTO `user` (`id`, `name`, `height`, `intro`) VALUES (3, '乃琳', 170.0, '奶琪琳!');
    

3.在springboot的配置文件中设置datasourcesqlite

  • # application-dev.yaml
    server:
      port: 80
    
    spring:
      datasource:
        # url最容易出错,如果使用相对于项目的相对地址,那么填入 jdbc:sqlite::resource:sqlit数据库所在位置
        # 注:
        # :resource: 指向项目的 resources 路径(resource前后两个 `:` 不能省略)
        url: jdbc:sqlite::resource:db/user.sqlite
        driver-class-name: org.sqlite.JDBC
        # username: 选用 sqlite 数据库不需要配置此项
        # password: 选用 sqlite 数据库不需要配置此项
        # DDL建表语句
        schema: classpath:db/schema.sql
        # DML添加数据
        data: classpath:db/data.sql
        initialization-mode: always
        continue-on-error: true
    mybatis-plus:
      mapper-locations: classpath:mapper/*Mapper.xml
      type-aliases-package: com.example.springbootsqlite.model
    

4. 数据源配好以后,其他操作跟普通 springboot项目一致,mybatismybatis-plus 可用

  • 完整demo代码在这里:springboot-sqlite
  • 注意:
    • sqlite中有些操作与mysql有一定差别,如sqlite中没有mysqlconcat函数`,基本数据类型也有一些差别。
      # mysql`CONCAT`函数
      SELECT * FROM `goods` WHERE `del` = 0 AND `name` LIKE CONCAT('%', #{name}, '%');
      # sqlite 中用`||`效果和`CONCAT`函数效果一致
      SELECT * FROM `goods` WHERE `del` = 0 AND `name` LIKE '%' || #{name} || '%'
      
    • 打包成jar包后运行可能出现初始数据乱码问题,可以在运行jar包时指定编码方式
      java -Dfile.encoding=utf-8 -jar springboot-sqlite-0.0.1-SNAPSHOT.jar
      
    • 大坑,在开发环境下,不要使用spring-boot-devtools工具,因为dev-tool工具会自动检测classpath路径下代码是否变更然后自动发布,导致springboot自动重启,从而使更新或保存的数据丢失。
posted @ 2022-06-14 11:19  kosihpc  阅读(8804)  评论(1编辑  收藏  举报