java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot整合MybatisPlus

SpringBoot项目整合MybatisPlus并使用SQLite作为数据库的过程

作者:Hello Dam

SQLite是一个紧凑的库,启用所有功能后,库大小可以小于 750KiB, 具体取决于目标平台和编译器优化设置, 内存使用量和速度之间需要权衡,这篇文章主要介绍了SpringBoot项目整合MybatisPlus并使用SQLite作为数据库,需要的朋友可以参考下

SQLite介绍

搭建项目

创建项目

修改pom.xml

因为使用SpringBoot 3.2.1 出了一些问题,下面改成2.5.14

<?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.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.14</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>org.dam</groupId>
    <artifactId>increment-backup-serve</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>increment-backup-serve</name>
    <description>increment-backup-serve</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <!-- web启动插件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--lombok插件-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- sqlite3驱动包 -->
        <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
            <version>3.21.0.1</version>
        </dependency>
        <!--mybatis-plus插件-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

使用Macbook pro运行项目,会报如下错误

Caused by: java.lang.Exception: No native library is found for os.name=Mac and os.arch=aarch64. path=/org/sqlite/native/Mac/aarch64

解决方案,修改版本

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

SQLite

查看SQLite是否安装

我的开发机是mac系统,自动了sqlite3,如果你们没有的话,要去安装,可以参考官方文档的快速开始:https://www.sqlite.org/quickstart.html

mac@MacdeMac-Pro ~ % sqlite3
SQLite version 3.39.4 2022-09-07 20:51:41
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.

创建数据库

从一个目录进入终端,创建数据库

mac@MacdeMac-Pro sql % sqlite3 increment-backup.db;
SQLite version 3.39.4 2022-09-07 20:51:41
Enter ".help" for usage hints.

查看数据库是否创建成功

sqlite> .databases
main: /Volumes/MacSpan/Projects/increment-backup/sql/DatabaseName.db r/w

创建成功,出现如下文件

创建数据表

创建数据表

sqlite> create table user
   ...> (
   ...>   id   INTEGER not null primary key autoincrement,
   ...>   name varchar(20)
   ...> );

查看数据表

sqlite> .tables
user

IDEA连接SQLite

连接成功

navicat连接SQLite数据库

连接成功

后端增删改查接口实现

MybatisX生成代码

如果没有安装如下插件的话,先安装一下

生成成功

创建如下项目结构,并粘贴所生成的代码过去

注意,mapper.xml的实体类引用要和你项目的一致

不会生成看这个

因为只是非常简单的案例,这里先不使用service包下的代码

User

package org.dam.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;
/**
 * 
 * @TableName user
 */
@TableName(value ="user")
@Data
public class User implements Serializable {
    /**
     * 
     */
    @TableId(type = IdType.AUTO)
    private Integer id;
    /**
     * 
     */
    private String name;
    @TableField(exist = false)
    private static final long serialVersionUID = 1L;
    @Override
    public boolean equals(Object that) {
        if (this == that) {
            return true;
        }
        if (that == null) {
            return false;
        }
        if (getClass() != that.getClass()) {
            return false;
        }
        User other = (User) that;
        return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
            && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName()));
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
        result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
        return result;
    }
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", id=").append(id);
        sb.append(", name=").append(name);
        sb.append(", serialVersionUID=").append(serialVersionUID);
        sb.append("]");
        return sb.toString();
    }
}

UserMapper

package org.dam.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.dam.entity.User;
/**
* @author mac
* @description 针对表【user】的数据库操作Mapper
* @createDate 2024-01-18 21:12:12
* @Entity generator.entity.User
*/
public interface UserMapper extends BaseMapper<User> {
}

UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.dam.mapper.UserMapper">
    <resultMap id="BaseResultMap" type="org.dam.entity.User">
            <id property="id" column="id" jdbcType="INTEGER"/>
            <result property="name" column="name" jdbcType="VARCHAR"/>
    </resultMap>
    <sql id="Base_Column_List">
        id,name
    </sql>
</mapper>

controller

package org.dam.controller;
import org.dam.entity.User;
import org.dam.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
 * @Author dam
 * @create 2024/1/18 20:37
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserMapper userMapper;
    /**
     * 增添数据
     */
    @GetMapping("/insert")
    public Object insert(String name) {
        User user = new User();
        user.setName(name);
        return userMapper.insert(user);
    }
    /**
     * 查询数据
     */
    @GetMapping("/show")
    public Object show() {
        return userMapper.selectList(null);
    }
    /**
     * 删除数据
     */
    @DeleteMapping("/delete")
    public Object delete(Integer id) {
        return userMapper.deleteById(id);
    }
    /**
     * 修改数据
     */
    @GetMapping("/update")
    public Object update(Integer id, String name) {
        User user = new User();
        user.setId(id);
        user.setName(name);
        return userMapper.updateById(user);
    }
}

创建配置文件application.yaml

注意url要对应sqlite数据库

# Tomcat
server:
  port: 8899
#spring
spring:
  datasource:
    #引用项目中的数据库文件
    driver-class-name: org.sqlite.JDBC
    url: jdbc:sqlite::resource:static/sqlite/increment-backup.db
    username:
    password:
  # 指定静态资源的路径
  web:
    resources:
      static-locations: classpath:/static/
#mybatis:
#  mapper-locations: classpath*:mapper/**/*.xml

启动类IncrementBackupServeApplication

package org.dam;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("org.dam.mapper")
public class IncrementBackupServeApplication {
    public static void main(String[] args) {
        SpringApplication.run(IncrementBackupServeApplication.class, args);
    }
}

测试

我这边使用接口测试工具Apifox来进行测试,使用Postman等其他工具也是可以的,不过我强烈推荐Apifox,感觉非常好用

插入用户

查询所有用户

修改用户名称

再查一次,修改成功

删除用户

再查一遍,删除成功

到此这篇关于SpringBoot项目整合MybatisPlus并使用SQLite作为数据库的文章就介绍到这了,更多相关SpringBoot整合MybatisPlus内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

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