SpringBoot整合MybatisPlus-分页

Springboot整合MybatisPlus-分页


一、MybatisPlus 简介

1.1 简介

MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window) 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

愿景

我们的愿景是成为 MyBatis 最好的搭档,就像 魂斗罗 中的 1P、2P,基友搭配,效率翻倍。

在这里插入图片描述

1.2 特性

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
  • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
  • 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
  • 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
  • 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
  • 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
  • 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
  • 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
  • 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
  • 内置性能分析插件:可输出 SQL 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
  • 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作

1.3 支持数据库

任何能使用 MyBatis 进行 CRUD, 并且支持标准 SQL 的数据库,具体支持情况如下,如果不在下列表查看分页部分教程 PR 您的支持。

  • MySQL,Oracle,DB2,H2,HSQL,SQLite,PostgreSQL,SQLServer,Phoenix,Gauss ,ClickHouse,Sybase,OceanBase,Firebird,Cubrid,Goldilocks,csiidb,informix,TDengine,redshift
  • 达梦数据库,虚谷数据库,人大金仓数据库,南大通用(华库)数据库,南大通用数据库,神通数据库,瀚高数据库,优炫数据库

1.4 框架结构

在这里插入图片描述

1.5 mybatis-plus依赖!

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.2</version>
</dependency>

二、SpringBoot+MyBaitsPlus 入门案例

2.1创建项目 + 添加pom.xml依赖

2.2.1 创建Spring Initializr项目

在这里插入图片描述

2.2.2 选择低版本 + 选择所需依赖

在这里插入图片描述

2.2.3 pom.xml 添加MybatisPlus依赖
<!--MybatisPlus依赖-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.2</version>
</dependency>
<!--分页依赖-->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.4.6</version>
</dependency>

2.2 编码

2.2.1 数据库 - 表

表名:tb_customer

-- 创建表
CREATE TABLE `tb_customer`  (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `remark` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `telephone` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `address` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `typeId` int NULL DEFAULT NULL,
  `createtime` date NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `FK50l46bmpv01y2ievd9f81roo`(`typeId`) USING BTREE,
  CONSTRAINT `FK50l46bmpv01y2ievd9f81roo` FOREIGN KEY (`typeId`) REFERENCES `tb_customer_type` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB AUTO_INCREMENT = 9 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC;
-- 添加数据
INSERT INTO `tb_customer` VALUES (1, '小菜鸟', '这是一个备注', '17373172188', '\r\n长沙科泰', 1, '2022-12-27');
INSERT INTO `tb_customer` VALUES (2, 'admin', '管理员', '13543567653', '长沙开\r\n福区', 2, '2022-12-27');
INSERT INTO `tb_customer` VALUES (3, '小羊苏西', '佩奇最好的朋友', '13235325389', '长沙岳麓区', 2, '2022-12-27');
INSERT INTO `tb_customer` VALUES (4, '天线宝宝', '传说可以中码的节目', '13643567653', '长沙雨花区', 3, '2022-12-29');
INSERT INTO `tb_customer` VALUES (5, '大象佩罗一', '不知道写什么', '13743567652', '长沙望城区', 1, '2022-12-27');
INSERT INTO `tb_customer` VALUES (6, '小狗丹尼', '汪汪汪', '13843567654', '长沙\r\n天心区', 4, '2022-12-16');
INSERT INTO `tb_customer` VALUES (8, 'lisi', '123', '123456789', '123', 1, '2019-09-07');
INSERT INTO `tb_customer` VALUES (12, '小白', '真的很白', '15588888', '广东东莞', 2, '2022-11-18');
2.2.2 配置文件application.properties修改为application.yml

注意:修改数据库名!!

server:
  port: 8089
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/数据库名?characterEncoding=utf-8&serverTimezone=GMT%2B8
    username: root
    password: root

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  type-aliases-package:
  mapper-locations: classpath:mapper/*.xml #sql语句文件
  global-config:
    db-config:
      logic-delete-field: deleted #逻辑删除
2.2.3 pojo实体层

实体类名:Customer

package com.it.pojo;

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 com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

@Data
@TableName(value = "tb_customer") // 当实体类名与表名不一样时,使用
public class Customer {
    //序列化
    @TableField(exist = false)
    private static final long serialVersionUID=1l;
    //标识为主键
    @TableId(type = IdType.AUTO)
    private Integer id;
    private String name;
    private String remark;
    private String telephone;
    private String address;
    private Integer typeid;
    //数据类型转换
    @DateTimeFormat(pattern = "yyyy-MM-dd") // 转换为date时间数据
    @JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8") //转换为json数据
    private Date createtime;
}
2.2.4 mapper接口层(又名dao层:数据访问层)

Mapper接口名:CustomerMapper

package com.it.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.it.pojo.Customer;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface CustomerMapper extends BaseMapper<Customer> {
}
2.2.5 service层 + 实现接口impl层(业务逻辑层)

service层:接口名:CustomerService

package com.it.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.it.pojo.Customer;

public interface CustomerService extends IService<Customer> {
}

impl层:实现名:

package com.it.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.mapper.CustomerMapper;
import com.it.pojo.Customer;
import com.it.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {
}
2.2.6 util 工具包 统一返回数据类型类(工具类)

统一返回数据类型类名:ResponseResult

package com.it.util;

/**
 * 数据统一放回类
 */
public class ResponseResult {
    private Integer state;
    private String msg;
    private Object data;

    public ResponseResult() {
        this.state = 200;
        this.msg = "成功";
    }

    public ResponseResult(Integer state, String msg) {
        this.state = state;
        this.msg = msg;
    }

    public ResponseResult(Integer state, String msg, Object data) {
        this.state = state;
        this.msg = msg;
        this.data = data;
    }

    public Integer getState() {
        return state;
    }

    public void setState(Integer state) {
        this.state = state;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}
2.2.7 config 配置包 MybatisPlus配置类

MybatisPlus配置类名:MybatisPlusConfig

package com.it.config;
/*
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
*/
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/*@Configuration用于定义配置类, 相当于 配置的头部
可替换xml配置文件,被注解的类内部包含有一个或多个被
@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext
或AnnotationConfigWebApplicationContext类进行扫描,
并用于构建bean定义,初始化Spring容器。 注意:@Configuration注解的配置类有如下要求:*/

@Configuration
public class MybatisPlusConfig {

    //@Configuration启动容器+@Bean注册Bean
    /**
     * mybatis拦截器   注册插件
     * @return
     */
   @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        // 初始化拦截器
        MybatisPlusInterceptor interceptor=new MybatisPlusInterceptor();
        // 添加分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

/*
    @Configuation等价于<Beans></Beans>
    @Bean等价于<Bean></Bean>
    @ComponentScan等价于<context:component-scan base-package="com.xxx"/>
    */
}
2.2.8 controller层 (控制层)

分页controller类名:PageController

package com.it.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class PageController {

    @RequestMapping("/{page}.html")
    public String toPage(String page){
        return page;
    }
}

接口测试controller类名:CustomerController

package com.it.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.it.pojo.Customer;
import com.it.service.CustomerService;
import com.it.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/customer")
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    //成功结果集
    public ResponseResult resultSucceed(Object object) {
        ResponseResult result = new ResponseResult();
        result.setData(object);
        result.setMsg("成功");
        result.setState(200);
        return result;
    }

    //失败结果集
    public ResponseResult resultLose(Object object) {
        ResponseResult result = new ResponseResult();
        result.setData(object);
        result.setMsg("失败");
        result.setState(404);
        return result;
    }

    @RequestMapping("/getAll")
    @ResponseBody
    public ResponseResult list() {
        List<Customer> list = customerService.list();
        ResponseResult result = new ResponseResult();
        result.setData(list);
        return result;
    }

    //http://localhost:8089/customer/findById/1
    @RequestMapping("/findById/{id}")
    @ResponseBody
    public ResponseResult findById(@PathVariable Integer id) {
        Customer list = customerService.getById(id);
        ResponseResult result = new ResponseResult();
        result.setData(list);
        return result;
    }

    @GetMapping("/removeId/{id}")
    @ResponseBody
    public ResponseResult removeId(@PathVariable Integer id) {
        boolean b = customerService.removeById(id);
        if (b) {
            ResponseResult result = this.resultSucceed(b);
            return result;
        } else {
            ResponseResult result = this.resultLose(b);
            return result;
        }
    }

    //http://localhost:8089/customer/addCustomer?name=小黑&remark=真的很黑&telephone=15588888&address=上海&typeid=2
    @RequestMapping("/addCustomer")
    @ResponseBody
    public ResponseResult addCustomer(Customer customer) {
        boolean b = customerService.save(customer);
        if (b) {
            ResponseResult result = this.resultSucceed(b);
            return result;
        } else {
            ResponseResult result = this.resultLose(b);
            return result;
        }
    }

    //http://localhost:8089/customer/updateCustomer?id=12&name=小黑&remark=真的很黑&telephone=15588888&address=上海&typeid=2
    @RequestMapping("/updateCustomer")
    @ResponseBody
    public ResponseResult updateCustomer(Customer customer) {
        boolean b = customerService.saveOrUpdate(customer);
        if (b) {
            ResponseResult result = this.resultSucceed(b);
            return result;
        } else {
            ResponseResult result = this.resultLose(b);
            return result;
        }

    }

    @RequestMapping("/list")
    @ResponseBody
    public ResponseResult list(@RequestParam(required = false, defaultValue = "1", value = "pageNum") Integer pageNum,
                               @RequestParam(required = false, defaultValue = "3", value = "pageSize") Integer pageSize) {
        Page<Customer> customerPage = new Page<>(pageNum, pageSize);
        customerService.page(customerPage);
        ResponseResult result = new ResponseResult();
        result.setData(customerPage);
        return result;
    }
}
				我们若已接受最坏的,就再没有什么损失。   --戴尔.卡耐基
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值