SpringBoot+Mybatis-Plus+MySQL8+Druid连接池的使用

一、SpringBoot简介:

Spring Boot 是一个用于创建独立的、基于 Spring 框架的应用程序的工具。使用 Spring Boot 可以更快速地搭建和部署应用,同时它集成了大量的开箱即用的功能和组件,使得开发变得更加简单。

二、SpringBoot使用流程:

1.创建一个SpringBoot项目:

  • 使用 Maven 或 Gradle 构建工具创建一个新的项目,可以使用 Spring Initializr 进行快速初始化。
  • 在项目中引入 spring-boot-starter-parent 作为父项目,以及其他需要的 starter 依赖,如 spring-boot-starter-web、spring-boot-starter-data-jpa 等。
  • java的版本为jdk8、SpringBoot的版本为2.7.14、IDEA为2021.2、MySQL为8版本、maven为3.6.3

2.打开pom.xml文件:

  • 添加父级依赖:
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.14</version>
</parent>
  • jdk版本:
<properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
</properties>
  • 添加完毕后:
复制代码
<?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 http://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.7.14</version>
    </parent>

    <groupId>com.qb.mptest</groupId>
    <artifactId>TestMyBatisframework</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
</project>
复制代码
  • 添加其他依赖:
复制代码
<dependencies>
        <!--web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--test-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--MyBatis-Plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>
        <!--MySQL-->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!--druid连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.16</version>
        </dependency>
        <!--日志-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
</dependencies>
复制代码

3.编写应用程序代码

3.1、配置相关:

  • SpringBoot程序入口类,通常使用@SpringBootApplication注解标记。
复制代码
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * Created with IntelliJ IDEA 2021.
 *
 * @Author: Mr Qin
 * @Date: 2023/11/29/23:01
 * @Description:启动类
 */
@SpringBootApplication
@EnableTransactionManagement
public class MpTestApplication {
    public static void main(String[] args) {
        SpringApplication.run(MpTestApplication.class, args);
        System.out.println("项目启动成功....");
    }
}
复制代码
  • 将application.properties文件后缀改为.yml(配置文件有三种格式properties、yaml、yml),yml格式比较简洁,下面编辑我们的配置(未使用druid连接池和对数据库密码加密):
复制代码
server:
  port: 8080  # 项目启动端口(默认8080)

spring:
  datasource:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/要使用的MySQL数据库名
      username: MySQ用户名
      password:  MySQL密码
复制代码
  • 使用druid连接池并对mysql数据库密码加密处理:
复制代码
server:
  port: 8080  # 项目启动端口(默认8080)

spring:
  datasource:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/要使用的MySQL数据库名
      username: MySQL用户名
      # password: MySQL密码(如123456)
      # (如123456)加密后得到的密码和私钥
      password: Juxe6O5zoJASPKcko2SQA705dCYqirnFe3G99r/CXh6KxDlyEBXqr6x0uw6ApOsGakfxI0TtlA3MTWBI3d92VA==
      druid:
        connect-properties:
          config.decrypt: true
          config.decrypt.key: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMm+z16KwRED0ftRQy9TR9lVnG1pAJmeVBRC84JxpHSqrmKg8joMWZiDM5XVVpNY7H+V0a7RQh/niR1TL4274oMCAwEAAQ==
        # 配置 connection-properties,启用加密,配置公钥。
        # 启动ConfigFilter
        filter:
          config:
            enabled: true
          slf4j:
            enabled: true


        initial-size: 5   # 初始化时建立物理连接的个数
        min-idle: 5       # 最小连接数
        max-active: 18    # 最大连接数
        max-wait: 6000    # 配置获取连接等待超时的时间
        min-evictable-idle-time-millis: 300000    # 连接保持空闲而不被驱逐的最小时间
        max-evictable-idle-time-millis: 600000    # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
        async-init: true
# 开启mybatis-plus标准日志输出
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
复制代码

3.2、编写业务逻辑代码,包括控制器、服务、数据访问对象等组件

3.2.1、结构目录:

 

3.2.2、代码编写

封装统一返回结果:

  • 状态码枚举类:
复制代码
package com.qb.mptest.comment;

import lombok.Getter;

/**
 * Created with IntelliJ IDEA 2021.
 *
 * @Author: Mr Qin
 * @Date: 2023/11/30/11:19
 * @Description:
 */
@Getter
public enum ResultCodeEnum {

    SUCCESS(200,"操作成功"),
    FAIL(-1,"操作失败"),
    PARAM_IS_INVALID(1001,"参数无效"),
    PARAM_TYPE_ERROR(1002,"参数类型错误"),
    ;

    private final Integer code;
    private final String msg;
    ResultCodeEnum(Integer code, String msg){
        this.code = code;
        this.msg = msg;
    }
}
复制代码
  • 统一返回对象R封装code(状态码)、message(返回信息)、data(返回数据):
复制代码
package com.qb.mptest.comment;

import lombok.Data;

import java.io.Serializable;

/**
 * Created with IntelliJ IDEA 2021.
 *
 * @Author: Mr Qin
 * @Date: 2023/11/30/10:50
 * @Description: 统一返回对象R
 */
@Data
public class R <T> implements Serializable {
    //返回码
    private Integer code;

    //返回说明
    private String msg;

    //返回数据
    private T data;

    /**
     * 自定义响应码与提示信息构造器
     * @param code 响应码
     * @param msg  提示消息
     */
    public R(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    /**
     * 自定义响应码与提示信息、数据返回构造器
     * @param code  响应码
     * @param msg   提示消息
     * @param data  返回数据
     */
    public R(Integer code, String msg, T data){
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    /**
     * 成功构造器  无返回数据
     * @param <T>
     * @return
     */
    public static <T> R<T> success(){
        return new R<>(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMsg());
    }

    /**
     * 成功构造器  有返回数据
     * @param data
     * @param <T>
     * @return
     */
    public static <T> R<T> success(T data){
        return new R<>(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMsg(), data);
    }

    /**
     * 失败构造器 无返回数据
     * @param <T>
     * @return
     */
    public static <T> R<T> error(){
        return new R<>(ResultCodeEnum.FAIL.getCode(), ResultCodeEnum.FAIL.getMsg());
    }

    /**
     * 失败构造器 自定义构造信息 无返回数据
     * @param msg  提示信息
     * @param <T>
     * @return
     */
    public static <T> R<T> error(String msg){
        return new R<>(ResultCodeEnum.FAIL.getCode(), msg);
    }

    /**
     * 失败构造器  有返回数据
     * @param data 返回数据
     * @param <T>
     * @return
     */
    public static <T> R<T> error(T data){
        return new R<>(ResultCodeEnum.FAIL.getCode(), ResultCodeEnum.FAIL.getMsg(), data);
    }
}
复制代码

mp分页插件:

复制代码
package com.qb.mptest.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created with IntelliJ IDEA 2021.
 *
 * @Author: Mr Qin
 * @Date: 2023/12/01/15:16
 * @Description:
 */
@Configuration
@MapperScan("com.qb.mptest.mapper")
public class MybatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}
复制代码

实体类及持久层:

  • 实体类Student(如我的数据库里面有一个Student表,属性包含id、name):
复制代码
package com.qb.mptest.entity;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.io.Serializable;

/**
 * Created with IntelliJ IDEA 2021.
 *
 * @Author: Mr Qin
 * @Date: 2023/11/30/9:59
 * @Description:
 */
@Data
@TableName("student")
public class Student implements Serializable {
    //设置主键自增,不使用mp框架的雪花算法
    //@TableId(value = "id", type = IdType.AUTO)
    private Long id;
    private String name;
}
复制代码
  • 映射接口StudentMapper(简单继承mp的BaseMapper<实体类>获得基本的crud功能):(添加@Repository注解为持久层组件)

注:@Repository注解是将持久层接口的实现类交给spring管理,并将数据访问异常封装为Spring的异常类型。

复制代码
package com.qb.mptest.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.qb.mptest.entity.Student;
import org.springframework.stereotype.Repository;

/**
 * Created with IntelliJ IDEA 2021.
 *
 * @Author: Mr Qin
 * @Date: 2023/11/30/10:04
 * @Description:
 */
@Repository
public interface StudentMapper extends BaseMapper<Student> {
}
复制代码

业务接口及其实现类:

  • 业务接口StudentService,继承IService<实体类>:
复制代码
package com.qb.mptest.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.qb.mptest.entity.Student;

/**
 * Created with IntelliJ IDEA 2021.
 *
 * @Author: Mr Qin
 * @Date: 2023/11/30/10:06
 * @Description:
 */
public interface StudentService extends IService<Student> {
}
复制代码
  • 业务接口实现类StudentServiceImpl,继承ServiceImpl<映射接口,实体类>,实现业务接口:(添加@Service注解标志为业务层组件)

注:@Service 注解是 Spring 框架中用来标注服务层组件的注解,它的作用是将标注的类注册为 Spring 容器中的 Bean,以便在其他组件中进行依赖注入等操作。

复制代码
package com.qb.mptest.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qb.mptest.entity.Student;
import com.qb.mptest.mapper.StudentMapper;
import com.qb.mptest.service.StudentService;
import org.springframework.stereotype.Service;


/**
 * Created with IntelliJ IDEA 2021.
 *
 * @Author: Mr Qin
 * @Date: 2023/11/30/10:06
 * @Description:
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
}
复制代码

控制器:

  • @Autowired 的作用是自动装配,它可以自动将一个类的实例注入到另一个类中,避免了手动创建对象的繁琐和容易出错的过程。

 

复制代码
package com.qb.mptest.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qb.mptest.comment.Params;
import com.qb.mptest.comment.R;
import com.qb.mptest.entity.Student;
import com.qb.mptest.service.StudentService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created with IntelliJ IDEA 2021.
 *
 * @Author: Mr Qin
 * @Date: 2023/11/30/10:09
 * @Description:
 */
@RestController
@RequestMapping("/student")
@CrossOrigin
public class StudentController {

    @Autowired
    private StudentService studentService;

    /**
     * 查询全部学生
     * @return
     */
    @GetMapping("/all")
    public R<List<Student>> FindAll(){
        List<Student> list = studentService.list();
        return R.success(list);
    }

    /**
     * 查询单个学生
     * @param id 学生Id
     * @return
     */
    @GetMapping("/{id}")
    public R<Student> FindById(@PathVariable("id") Long id){
        return R.success(studentService.getById(id));
    }

    /**
     * 新增学生
     * @param student 学生实体
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Student student){
        studentService.save(student);
        return R.success();
    }

    /**
     * 根据Id修改学生
     * @param student 学生实体
     * @return
     */
    @PostMapping("/update")
    public R<String> update(@RequestBody Student student){
        studentService.updateById(student);
        return R.success();
    }

    /**
     * 根据Id删除学生
     * @param id 学生Id
     * @return
     */
    @PostMapping("/del/{id}")
    public R<String> delete(@PathVariable Long id){
        studentService.removeById(id);
        return R.success();
    }

    /**
     * 分页查询
     * @param params
     * @return
     */
    @GetMapping("/page")
    public R<Page> StudentPage(@Param("params") Params params){
        //分页构造器
        Page<Student> page = new Page<>(params.getCurrent(), params.getSize());
        //条件构造器
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
        //排序条件
        //queryWrapper.orderByAsc(Student::getId);

        //进行分页查询
        studentService.page(page, queryWrapper);
        return R.success(page);
    }

}
复制代码

 

posted @   qinbmake  阅读(1716)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示