• SpringBoot笔记:SpringBoot集成MyBatisPlus、Sqlite实战


    前言

        时间关系,不做太多解释,sqlite 是一个很轻量级的数据库,可以满足日常 sql 的需求,如果不需要使用像 mysql 那样重量级的数据库可以考虑使用 sqllite。

    优缺点

    优点

    • SQLite 是一个非常轻量级的数据库。 因此在电脑,手机,相机,家用电子设备等设备的嵌入式软件是非常好的选择。
    • SQLite 的数据存储非常简单高效。 当您需要存储文件存档时,SQLite可以生成较小数据量的存档,并且包含常规ZIP存档的大量元数据。
    • SQLite 可以用作临时数据集,以对应用程序中的一些数据进行一些处理。
    • SQLite 数据库中,数据查询非常简单。 您可以将数据加载到SQLite内存数据库中,并随时提取数据。可以按照您想要的方式提取数据。
    • SQLite 提供了一种简单有效的方式来处理数据,而不是以内存变量来做数据处理。 例如:如果您正在开发一个程序,并且有一些记录要对其进行一些计算。 然后,您可以创建一个SQLite数据库并在其中插入记录,查询,可以选择记录并直接进行所需的计算。
    • SQLite 非常容易学习和使用。它不需要任何安装和配置。只需复制计算机中的SQLite库,就可以创建数据库了。

    缺点

        SQLite 一般用于处理小到中型数据存储,对于高并发高流量的应用不适用。

    实战演练

    代码结构

    代码整体结构

    pom.xml 配置

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    	<parent>
    		<groupId>org.example</groupId>
    		<artifactId>springboot-learning-parents</artifactId>
    		<version>1.0-SNAPSHOT</version>
    	</parent>
    
    	<groupId>springboot-demo</groupId>
    	<artifactId>springboot-sqlite</artifactId>
    	<version>1.0-SNAPSHOT</version>
    	<name>springboot-sqlite</name>
    
    	<description>springboot集成sqlite</description>
    	<properties>
    		<start-class>com.demo.SpringbootSqliteApplication</start-class>
    		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    		<java.version>1.8</java.version>
    		<mybatisplus.version>3.5.1</mybatisplus.version>
    		<freemaker.version>2.3.31</freemaker.version>
    		<mysql.version>8.0.28</mysql.version>
    	</properties>
    	<dependencies>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-devtools</artifactId>
    		</dependency>
    
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-web</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-test</artifactId>
    			<scope>test</scope>
    		</dependency>
    		<dependency>
    			<groupId>org.projectlombok</groupId>
    			<artifactId>lombok</artifactId>
    		</dependency>
    
    		<!-- mybatis-plus 所需依赖  -->
    		<dependency>
    			<groupId>com.baomidou</groupId>
    			<artifactId>mybatis-plus-boot-starter</artifactId>
    			<version>${mybatisplus.version}</version>
    		</dependency>
    		<dependency>
    			<groupId>com.baomidou</groupId>
    			<artifactId>mybatis-plus-generator</artifactId>
    			<version>${mybatisplus.version}</version>
    		</dependency>
    		<dependency>
    			<groupId>org.freemarker</groupId>
    			<artifactId>freemarker</artifactId>
    			<version>2.3.31</version>
    		</dependency>
    
    		<!-- sqlite 依赖包 -->
    		<dependency>
    			<groupId>org.xerial</groupId>
    			<artifactId>sqlite-jdbc</artifactId>
    			<version>3.36.0.3</version>
    		</dependency>
    	</dependencies>
    
    	<build>
    		<plugins>
    			<plugin>
    				<groupId>org.springframework.boot</groupId>
    				<artifactId>spring-boot-maven-plugin</artifactId>
    			</plugin>
    		</plugins>
    	</build>
    </project>
    
    
    • 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
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80

    application.yml 配置

    #端口,项目上下文
    server:
      port: 8080
      servlet:
        context-path: /springboot-sqlite
    
    spring:
      datasource:
        username: leo825
        password: 1WSX@357wj
        url: jdbc:sqlite:D:/program/sqlite3/db/pro.db
        driver-class-name: org.sqlite.JDBC
        # 初始化表
        schema: classpath:schema.sql
        # 初始化数据
        data: classpath:data.sql
        initialization-mode: always
        continue-on-error: true
    
    
    # mybatis-plus 配置
    mybatis-plus:
      mapper-locations: classpath*:/mapper/**/*.xml
      #实体扫描,多个package用逗号或者分号分隔
      typeAliasesPackage: com.dmo.entity
      global-config:
        #数据库相关配置
        db-config:
          #主键类型  AUTO:"数据库ID自增", INPUT:"用户输入ID", ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID";
          id-type: AUTO
          #字段策略 IGNORED:"忽略判断",NOT_NULL:"非 NULL 判断"),NOT_EMPTY:"非空判断"
          field-strategy: NOT_NULL
          #驼峰下划线转换
          column-underline: true
          logic-delete-value: -1
          logic-not-delete-value: 0
        banner: false
      #原生配置
      configuration:
        # 打印sql
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
        map-underscore-to-camel-case: true
        cache-enabled: false
        call-setters-on-nulls: true
        jdbc-type-for-null: 'null'
    
    # 日志输出配置
    logging:
      level:
        root: INFO
        org:
          springframework:
            security: WARN
            web: ERROR
      file:
        path: ./logs
        name: './logs/sqlite-demo.log'
      pattern:
        file: '%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}:%L - %msg%n'
        console: '%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}:%L - %msg%n'
    
    • 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

    schema.sql

    create table if not exists t_user (
    	`id`       int  primary  key not null ,
    	`username` char (50) not null,
    	`pwd`      char(50) not null,
    	`create_time` datetime not null,
    	`update_time` datetime
    ) ;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    data.sql

    insert into t_user(id, username, pwd, create_time, update_time) values (1,'zhhangsan','1222', datetime('2022-07-05 20:35:30.30'), NULL)
    
    • 1

    mapper

    package com.demo.service.impl;
    
    import com.demo.entity.User;
    import com.demo.mapper.UserMapper;
    import com.demo.service.IUserService;
    import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    import org.springframework.stereotype.Service;
    
    /**
     * <p>
     * 用户表 服务实现类
     * </p>
     *
     * @author Leo825
     * @since 2022-07-05
     */
    @Service
    public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    service

    package com.demo.service;
    
    import com.demo.entity.User;
    import com.baomidou.mybatisplus.extension.service.IService;
    
    /**
     * <p>
     * 用户表 服务类
     * </p>
     *
     * @author Leo825
     * @since 2022-07-05
     */
    public interface IUserService extends IService<User> {
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    impl 实现类:

    package com.demo.service.impl;
    
    import com.demo.entity.User;
    import com.demo.mapper.UserMapper;
    import com.demo.service.IUserService;
    import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    import org.springframework.stereotype.Service;
    
    /**
     * <p>
     * 用户表 服务实现类
     * </p>
     *
     * @author Leo825
     * @since 2022-07-05
     */
    @Service
    public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    controller

    package com.demo.controller;
    
    
    import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
    import com.baomidou.mybatisplus.core.metadata.IPage;
    import com.baomidou.mybatisplus.core.toolkit.StringUtils;
    import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
    import com.demo.base.Result;
    import com.demo.entity.User;
    import com.demo.service.IUserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.List;
    
    /**
     * controller 测试
     *
     */
    @RestController
    @RequestMapping("/user")
    public class UserController {
    
        /**
         * 构造方法注入
         */
        @Autowired
        IUserService userService;
    
    
        /**
         * 保存数据
         *
         * @return
         */
        @GetMapping("/save")
        public Result save() {
            User user = new User();
            user.setId(10);
            user.setUsername("miaolinlin");
            user.setPwd("121212");
            userService.save(user);
            return new Result().ok(user);
        }
    
        /**
         * 修改数据
         *
         * @param id
         * @return
         */
        @GetMapping("/update")
        public Result update(Integer id) {
            User user = new User();
            user.setId(id);
            user.setPwd("1111111111");
            userService.updateById(user);
            return new Result().ok("{}");
        }
    
        @GetMapping("/list")
        public Result list() {
            // 返回所有
            List<User> list = userService.list();
            return new Result().ok(list);
        }
    
        @GetMapping("/listByContion")
        public Result listByContion() {
            /**
             * 条件查询, 通过QueryWrapper来实现查询的条件:
             * eq: 代表相等
             * like: 模糊匹配
             * orderBy: 排序
             * in, notin
             * 大于,小于,between等
             */
            List<User> list = userService.list(new LambdaQueryWrapper<User>()
                    // 查询年龄=11的
                    .eq(User::getUsername, "miao")
                    // 模糊匹配
                    .like(User::getPwd, "%111%")
                    // 排序,按照创建时间
                    .orderByDesc(User::getCreateTime)
            );
            return new Result().ok(list);
        }
    
        /**
         * 根据id获取数据
         *
         * @param id
         * @return
         */
        @GetMapping("/getById")
        public Result getById(Integer id) {
            User user = userService.getById(id);
            return new Result().ok(user);
        }
    
        /**
         * 删除数据
         *
         * @param id
         * @return
         */
        @GetMapping("/delete")
        public Result delete(Integer id) {
            userService.removeById(id);
            return new Result().ok("success");
        }
    
        /**
         * 分页查询
         *
         * @param pageNum
         * @param pageSize
         * @param name
         * @return
         */
        @GetMapping("/page")
        public Result page(int pageNum, int pageSize, String name) {
            IPage<User> page = new Page<>(pageNum, pageSize);
    
            IPage<User> page1 = userService.page(page, new LambdaQueryWrapper<User>()
                    // 主要演示这里可以加条件。在name不为空的时候执行
                    .like(StringUtils.isNotEmpty(name), User::getUsername, "%" + name + "%"));
    
            return new Result().ok(page1);
        }
    }
    
    • 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
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133

    总结

    springboot 整合 sqllite 和 mysql 差不多,代码库地址如下:

    https://gitee.com/leo825/springboot-learning-parents.git

  • 相关阅读:
    centos7安装confluence7.16.5
    【uniapp】uniapp开发app在线预览pdf文件
    CentOS 7 上安装 Oracle 11g 数据库
    npm ERR! code ERESOLVE
    废液收集系统物联网远程监控解决方案
    关于 byte 的范围
    Spring Cloud Gateway网关两种负载均衡
    高薪程序员&面试题精讲系列132之微服务之间如何进行通信?服务熔断是怎么回事?你熟悉Hystrix吗?
    维纳滤波器小结
    [架构之路-239]:目标系统 - 纵向分层 - 中间件middleware
  • 原文地址:https://blog.csdn.net/u011047968/article/details/125623733