SQLite使用入门

  1. SQLite数据库概述
  2. 在Spring Boot框架中使用SQLite数据库
    1. 基础配置
    2. 数据表DDL
  3. SQLite访问工具

SQLite数据库概述

在某些场景下使用SQLite文件数据库替代MySQL数据库是非常值得的,比如存储的数据量可控,业务查询简单。
相比起MySQL,PostgreSQL这样的大型数据库,SQLite文件数据库仅支持有限的数据类型;SQLite支持的SQL语法与MySQL/PostreSQL也有不尽相同,关于SQLite的介绍参考SQLite 教程

在Spring Boot框架中使用SQLite数据库

基础配置

组件依赖:

<!-- 使用JDBC访问 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<!-- SQLite JDBC驱动 -->
<dependency>
    <groupId>org.xerial</groupId>
    <artifactId>sqlite-jdbc</artifactId>
    <version>3.44.1.0</version>
</dependency>

<!-- 集成MyBatis -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>${version.mybatis.starter}</version>
</dependency>

数据源配置:

@Configuration
public class DataSourceConfig {
    @Bean
    public DataSource dataSource() {
        SQLiteDataSource dataSource = new SQLiteDataSource();
        // 指定SQLite数据库文件地址
        dataSource.setUrl("jdbc:sqlite:C:\\Users\\test\\sample.db");
        return dataSource;
    }
}

MyBatis配置:

@Configuration
@MapperScan("com.sample.mapper")
public class MyBatisConfig {
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);

        // 设置MyBatis配置
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.getTypeAliasRegistry().registerAliases("com.sample.po");
        configuration.getTypeHandlerRegistry().register("com.sample.handler");

        // 设置方言
        configuration.setDatabaseId("sqlite");

        sessionFactory.setConfiguration(configuration);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/*.xml"));

        return sessionFactory.getObject();
    }
}

SQLite本身不支持Boolean类型,如果数据实体中存在Boolean类型属性,需要进行类型转换,可以配置全局类型处理器:

package com.sample.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

@MappedTypes(Boolean.class)
@MappedJdbcTypes(JdbcType.INTEGER)
public class BooleanTypeHandler extends BaseTypeHandler<Boolean> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Boolean parameter, JdbcType jdbcType) throws SQLException {
        ps.setInt(i, parameter ? 1 : 0);
    }

    @Override
    public Boolean getNullableResult(ResultSet rs, String columnName) throws SQLException {
        int value = rs.getInt(columnName);
        return rs.wasNull() ? null : value == 1;
    }

    @Override
    public Boolean getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        int value = rs.getInt(columnIndex);
        return rs.wasNull() ? null : value == 1;
    }

    @Override
    public Boolean getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        int value = cs.getInt(columnIndex);
        return cs.wasNull() ? null : value == 1;
    }
}

Spring Boot应用配置配置:

## 应用启动时初始化数据库表
spring.datasource.platform=sqlite
spring.datasource.initialization-mode=always
spring.datasource.schema=classpath:sql/schema.sql

## 集成MyBatis
## 检查MyBatis的配置文件
mybatis.check-config-location=true
## 指定MyBatis配置文件路径
mybatis.config-location=classpath:/mybatis-config.xml
## 注册XML映射器
mybatis.mapper-locations=classpath:/mapper/**/*.xml
## 指定POJO别名设置所在包
mybatis.type-aliases-package=com.sample.po
## 指定Java类型处理器所在包
mybatis.type-handlers-package=com.sample.handler
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.executor-type=simple

数据表DDL

将如下创建数据库表的DDL语句保存到classpath:sql/schema.sql文件中。

CREATE TABLE IF NOT EXISTS user (
    id INTEGER PRIMARY KEY AUTOINCREMENT, -- 主键
    acct TEXT NOT NULL,                   -- 账号名称
    age INTEGER NOT NULL,                 -- 年龄
    addr TEXT NOT NULL,                   -- 地址
    ctime INTEGER NOT NULL,               -- 创建时间戳
    mtime INTEGER NOT NULL                -- 修改时间戳
);

完成上述准备工作以后,就可以像使用MySQL那样通过MyBatis操作数据库表了。

SQLite访问工具

推荐使用开源,跨平台的SQLite数据库管理工具:SQLiteStudio

【参考】
SQLite 教程
关于SQLite的注释


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达,在下面评论区告诉我^_^^_^