SpringBoot中如何使用MyBatis访问Sqlite3数据库

分类:计算机 | 数据库 | 综合 148
更新:2021-03-18 17:11:08
编辑

首先在pom中引用Sqlite3访问驱动包

<!-- sqlite3驱动包 -->
<dependency>
    <groupId>org.xerial</groupId>
    <artifactId>sqlite-jdbc</artifactId>
    <version>3.27.2.1</version>
</dependency>

在yml中配置Sqlite数据源连接参数

  # Sqlite数据库配置
  sqlitedatasource:
    driver-class-name: org.sqlite.JDBC
    url: jdbc:sqlite:C:\Users\Administrator\Desktop\xxx.db
    username:
    password:

Sqlite数据源配置

package com.yuanjingyan.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.sqlite.SQLiteDataSource;

import javax.sql.DataSource;

//表示这个类是一个配置类
@Configuration
//配置mybatis接口类放置的地方
@MapperScan(basePackages = "com.yuanjingyan.mappersqlite", sqlSessionFactoryRef = "sqliteSqlSessionFactory")
public class SqliteDataSourceConfig {
    //将这个对象放入Spring容器中
    @Bean(name = "sqliteDataSource")
    //读取yml中的数据库配置参数,映射成为一个对象,prefix表示参数的前缀
    @ConfigurationProperties(prefix="spring.sqlitedatasource") //告诉自动加载配置的属性
    public DataSource sqlserverDataSource() {
        SQLiteDataSource ds=new SQLiteDataSource();
        return ds;
    }

    @Bean(name = "sqliteSqlSessionFactory")
    // @Qualifier表示查找Spring容器中名字为sqliteDataSource的对象
    public SqlSessionFactory sqliteSqlSessionFactory(@Qualifier("sqliteDataSource") DataSource datasource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                // 设置mybatis的xml所在位置
                new PathMatchingResourcePatternResolver().getResources("classpath*:sqlitemybatis/*.xml"));
        return bean.getObject();
    }

    @Bean("sqliteSqlSessionTemplate")
    public SqlSessionTemplate sqlitesqlsessiontemplate(
            @Qualifier("sqliteSqlSessionFactory") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
    }
}