• SpringBoot整合JPA+SQLite


    背景介绍

    由于项目需求,要求能用一款不需要部署,并且可以跨平台使用,并且支持事务管理的关系型数据,我的第一问题就是为啥不能采用类似MySQL或者Oracle这一类的关系型数据库,并且它们的部署其实也不是很繁琐,他们说服务器不需要额外部署数据库,我的第一反映就是SQLite。
    至于是JAP或者MyBatis还是什么其他的ORM框架,这些都是无所谓的。

    SQLite安装以及生成db库

    SQLite官网下载地址

    在这里插入图片描述
    由于本人使用的是window环境,具体其他的操作系统,均可按照包名下载,下载完成后,解压到桌面
    在这里插入图片描述
    进入dos窗口后,输入

    C:\Users\xxxxx\Desktop\sqlite-tools-win32-x86-3390400>sqlite3
    SQLite version 3.39.4 2022-09-29 15:55:41
    Enter ".help" for usage hints.
    Connected to a transient in-memory database.
    Use ".open FILENAME" to reopen on a persistent database.
    sqlite> .open demo.db
    sqlite>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • sqlite3 打开SQLite数据库工具(窗口)
    • .open demo.db(生成并打开一个叫demo的db库)
      在返回sqlite安装包的目录下就会成一个一个db文件
      在这里插入图片描述
      注意
    • SQLite一些特性可以研究一下,比如免费开源版本是不支持数据库登录和密码的
    • db文件不能随便打开,可以通过数据库可视化工具打开,一般工具都是支持的,如果强行打开,里面的数据就GG了
    • db文件随处使用,只要有驱动均可使用并且实现CRUD
    • 它的亮点是轻量以及便捷,自然和大型关系型数据库相比那就是蚂蚁和大象的区别,不过麻雀虽小,五脏基本齐全,说这个的原因是告诉各位选它的话,可能它的某一些特性是阉割的。

    创建SpringBoot项目

    具体创建项目过程不说了,直接上代码吧,在创建勾选依赖的时候,只需要勾选一个web就可以了,其他都不需要

    POM文件所需要的依赖

            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-data-jpaartifactId>
            dependency>
            <dependency>
                <groupId>com.enigmabridgegroupId>
                <artifactId>hibernate4-sqlite-dialectartifactId>
                <version>0.1.2version>
            dependency>
            <dependency>
                <groupId>org.xerialgroupId>
                <artifactId>sqlite-jdbcartifactId>
                <version>3.21.0.1version>
            dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    其他的基础依赖包就不展示了,比如lombok这些,Junit等等。

    配置数据源

    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.jdbc.DataSourceBuilder;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.sqlite.SQLiteDataSource;
    
    import javax.sql.DataSource;
    
    
    @Configuration
    public class DataSourceConfig {
        @Value("${db.url}")
        private String dbUrl;
    
        @Bean(destroyMethod = "", name = "EmbeddedDataSource")
        public DataSource dataSource() {
            DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
            dataSourceBuilder.driverClassName("org.sqlite.JDBC");
            dataSourceBuilder.url(dbUrl);
            dataSourceBuilder.type(SQLiteDataSource.class);
            return dataSourceBuilder.build();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    配置文件中配置DB文件的url

    db:
      url: jdbc:sqlite::resource:db/simpleio.db
    
    • 1
    • 2

    注意了,看见我的路径的了,:resource 是指在项目工程下的resources下的db文件下的一个db文件

    在这里插入图片描述

    配置JAP

    我们这里就不采取yml的配置方式

    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
    import org.springframework.orm.jpa.JpaTransactionManager;
    import org.springframework.orm.jpa.JpaVendorAdapter;
    import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
    import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
    import org.springframework.transaction.annotation.EnableTransactionManagement;
    
    import javax.persistence.EntityManagerFactory;
    import javax.sql.DataSource;
    
    @Configuration
    @EnableJpaRepositories(
    		// 扫描 Repository 文件 (接口)
            basePackages = Repository 文件 (接口)文件路径,
            transactionManagerRef = "jpaTransactionManager",
            entityManagerFactoryRef = "localContainerEntityManagerFactoryBean"
    )
    @EnableTransactionManagement
    public class JpaConfig {
        @Autowired
        @Bean
        public JpaTransactionManager jpaTransactionManager(@Qualifier(value = "EmbeddedDataSource") DataSource dataSource, EntityManagerFactory entityManagerFactory) {
            JpaTransactionManager jpaTransactionManager
                    = new JpaTransactionManager();
            jpaTransactionManager.setEntityManagerFactory(entityManagerFactory);
            jpaTransactionManager.setDataSource(dataSource);
    
            return jpaTransactionManager;
        }
    
        @Autowired
        @Bean
        LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean(@Qualifier(value = "EmbeddedDataSource") DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
            LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean
                    = new LocalContainerEntityManagerFactoryBean();
            localContainerEntityManagerFactoryBean.setDataSource(dataSource);
    		// 这里要跟你自己设定的pojo类包路径
            localContainerEntityManagerFactoryBean.setPackagesToScan(pojo类包路径);
            localContainerEntityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter);
            return localContainerEntityManagerFactoryBean;
        }
    
        @Bean
        public JpaVendorAdapter jpaVendorAdapter() {
            HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
            hibernateJpaVendorAdapter.setGenerateDdl(true); // 是否支持ddl
            hibernateJpaVendorAdapter.setShowSql(true); // 是否控制台输入打印执行SQL语句
            hibernateJpaVendorAdapter.setDatabasePlatform("com.enigmabridge.hibernate.dialect.SQLiteDialect");
            return hibernateJpaVendorAdapter;
        }
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58

    测试效果

    创建pojo类

    
    import com.fasterxml.jackson.databind.annotation.JsonSerialize;
    import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
    import lombok.*;
    import org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration;
    
    import javax.persistence.*;
    
    /**
     * 账户
     *
     * @author lvxiwei
     * @since 2022-11-11
     */
    @Entity
    @Table(name = "account")
    @AllArgsConstructor
    @NoArgsConstructor
    @Getter
    @Setter
    @ToString
    public class Account extends JpaRepositoriesAutoConfiguration {
        /**
         * 自增主键ID
         */
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @JsonSerialize(using = ToStringSerializer.class)
        private Long id;
        /**
         * 登录用户名
         */
        private String username;
        /**
         * 登录密码
         */
        private String password;
        /**
         * 用户邮箱
         */
        private String email;
        /**
         * 用户类型 1 系统账户 2 自定义账户
         */
        private Long type;
        /**
         * 用户状态
         */
        private Long status;
    
        /**
         * 创建人
         */
        private Long creator;
    
        /**
         * 最近一次修改人
         */
        private Long modifier;
    
        /**
         * 创建日期
         */
        private Long createDate;
        /**
         * 最近一次修改日期
         */
        private Long modificationDate;
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71

    创建Repository 接口文件

    
    import com.personloger.model.pojo.Account;
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
    
    public interface AccountRepo extends JpaRepository<Account, Long>, JpaSpecificationExecutor {
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    业务层

    
    import com.personloger.dao.AccountRepo;
    import com.personloger.model.pojo.Account;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.stereotype.Service;
    
    import javax.annotation.Resource;
    import java.util.List;
    
    @Service
    @Slf4j
    public class AccountService {
    
        @Resource
        private AccountRepo accountRepo;
    
    
        public void save() {
            Account account = new Account();
            account.setUsername("admin");
            account.setPassword("123456");
            account.setEmail("louis0523@foxmail.com");
            account.setType(1L);
            account.setStatus(1L);
            account.setCreator(1L);
            account.setModifier(1L);
            account.setCreateDate(System.currentTimeMillis());
            account.setModificationDate(System.currentTimeMillis());
            Account save = accountRepo.save(account);
            System.out.println("==================>" + save.toString());
        }
    
        public List<Account> getList() {
          return   accountRepo.findAll();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37

    建表语句

    create table account
    (
        id               integer not null
            primary key autoincrement,
        username         TEXT,
        password         TEXT,
        email            TEXT,
        type             integer,
        status           integer,
        createDate       integer,
        modificationDate integer,
        creator          bigint,
        modifier         bigint
    );
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    测试结果展示

    在这里插入图片描述

  • 相关阅读:
    Otter改造 增加springboot模块和HTTP调用功能
    56.合并区间 | 1288.删除被覆盖的区间 | 986.区间列表的交集
    使用C#创建服务端Web API
    运筹学-单纯形法-代码实现(包含做题的每一步骤)
    工具篇--分布式定时任务springBoot--elasticjob简单使用(1)
    技术学习:Python(16)|lxml模块和Xpath(爬虫篇)
    shell
    vue 对axios进行封装
    Qt在Linux内核中的应用及解析(qtlinux内核)
    Jenkins从入门到精通面试题及参考答案(3万字长文)
  • 原文地址:https://blog.csdn.net/weixin_44922964/article/details/127808230