java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot加载SQLite数据源

SpringBoot加载SQLite数据源方式

作者:咖啡Beans

文章介绍了SpringBoot中配置SQLite数据源的流程,包括DBeaver连接数据库、执行建表与数据插入、引入依赖、初始化连接、定义实体类与Mapper,以及测试查询操作,同时提及多数据源适配的扩展方式

摘要

本文演示SpringBoot中单独使用SQLite数据源的场景写法。

示例步骤

1)打开dbeaver选择sqlite连接

2)执行建表语句,并新增数据

-- 用工具连接sqlite库,执行建表DDL初始化数据库
-- 文件存放在src/main/resources/sqlite/my_sqlite.db

CREATE TABLE IF NOT EXISTS user
(
 id          INTEGER primary key autoincrement,
 name        VARCHAR,
 create_time VARCHAR
);

INSERT INTO "user"
(id, name, create_time)
VALUES(1, 'sqlite名字', '2025-01-01 00:00:00');

3)引入依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <groupId>org.springframework.boot</groupId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-undertow</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.xerial</groupId>
        <artifactId>sqlite-jdbc</artifactId>
    </dependency>
</dependencies>

4)初始化sqlite数据源连接配置

package org.coffeebeans.config;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceCreator;
import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.creator.hikaricp.HikariDataSourceCreator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.io.File;

/**
 * <li>ClassName: SqliteDbConfig </li>
 * <li>Author: OakWang </li>
 * 初始化数据源
 */
@Slf4j
@Configuration
public class SqliteDbConfig {
    @Autowired
    private DataSource dataSource;

    @Autowired
    private HikariDataSourceCreator dataSourceCreator; //需要显式指定HikariDataSourceCreator

    @PostConstruct
    public void initDatasource() {
       log.info("===开始数据源初始化===");
       File file = FileUtil.file(ResourceUtil.getResource("sqlite/my_sqlite.db"));  // 获取sqlite数据库文件
       DataSourceProperty dataSourceProperty = new DataSourceProperty(); // 创建数据源属性对象
       dataSourceProperty.setUrl("jdbc:sqlite:" + file.getAbsolutePath()); // 设置数据库连接URL
       dataSourceProperty.setDriverClassName("org.sqlite.JDBC"); // 设置数据库驱动类名
       DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource; // 获取动态数据源实例
       DataSource masterDataSource =  dataSourceCreator.createDataSource(dataSourceProperty); // 根据属性创建数据源
       ds.addDataSource("master", masterDataSource); // 添加数据源到动态数据源中,命名为master
       log.info("===数据源初始化完毕===");
    }

    /*
       启动输出日志:
       c.b.d.d.DynamicRoutingDataSource         : dynamic-datasource initial loaded [0] datasource,Please add your primary datasource or check your configuration
       org.coffeebeans.config.SqliteDbConfig          : ===开始数据源初始化===
       c.b.d.d.DynamicRoutingDataSource         : dynamic-datasource - add a datasource named [master] success
       org.coffeebeans.config.SqliteDbConfig          : ===数据源初始化完毕===
       org.coffeebeans.SqliteTest               : Started SqliteTest in 2.668 seconds (JVM running for 3.577)
       com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
       com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
     */

}

5)定义实体类

package org.coffeebeans.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;

/**
 * <li>ClassName: SqliteUser </li>
 * <li>Author: OakWang </li>
 */
@Data
@TableName("user")
publicclass SqliteUser implements Serializable {

    private static final long serialVersionUID = 6133167221453780808L;

    @TableId(type = IdType.AUTO)
    private Long id;

    @TableField("name")
    private String name;

    @TableField("create_time")
    private String createTime;

}

6)定义Mapper

package org.coffeebeans.mapper;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.coffeebeans.entity.SqliteUser;
import java.util.List;

@Mapper
public interface SqliteUserMapper {

    @Select("select id,name,create_time as createTime from user where id = 1")
    List<SqliteUser> selectBySearchInSqlite();

}

7)测试查询

package org.coffeebeans;

import lombok.extern.slf4j.Slf4j;
import org.coffeebeans.mapper.SqliteUserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * <li>ClassName: org.org.org.coffeebeans.SqliteTest </li>
 * <li>Author: OakWang </li>
 */
@Slf4j
@SpringBootTest
public class SqliteTest {

    @Autowired
    private SqliteUserMapper sqliteUserMapper;

    @Test
    void test() {
       log.info("Sqlite查询:" + sqliteUserMapper.selectBySearchInSqlite());
       /*
          Sqlite查询:[SqliteUser(id=1, name=sqlite名字, createTime=2025-01-01 00:00:00)]
        */
    }

}

总结

以上我们了解了SpringBoot中单独使用SQLite数据源的场景写法,除此之外还有更简便的使用场景,比如多数据源适配。

这些仅为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文