一、前期准备:

1. 创建测试表:用户并插入数据

create table user
(
	id int(20) auto_increment comment 'id',
	username varchar(20) null comment '用户名',
	gender tinyint null comment '''0保密 1男 2女',
	password varchar(32) null comment '密码',
	age int(4) null comment '年龄',
	create_time datetime null comment '创建时间',
	constraint user_pk
		primary key (id)
)
comment '用户表';

在这里插入图片描述

2. 导入mybatis-plus依赖

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

3. 连接数据库:application.yaml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
    url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true

server:
  port: 9090

mybatis-plus:
  mapper-locations: classpath:mapper/*.xml
  # 控制台打印sql语句
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

4. 生成实体类

@Data
@TableName(value = "user")
public class UserEntity{

    /**
     * id
     */
    @TableId
    private Long id;
    
    /**
     * 用户名
     */
    private String username;

    /**
     * 密码
     */
    private String password;

    /**
     * 0保密 1男 2女
     */
    private Integer gender;

    /**
     * 年龄
     */
    private Integer age;
}

5. 配置类

参考:分页插件 - PaginationInnerInterceptor

@Configuration
@EnableTransactionManagement
public class MybatisPlusConfig{

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        paginationInnerInterceptor.setOptimizeJoin(true);
        paginationInnerInterceptor.setDbType(DbType.MYSQL);
        paginationInnerInterceptor.setOverflow(true);
        interceptor.addInnerInterceptor(paginationInnerInterceptor);
        OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor = new OptimisticLockerInnerInterceptor();
        interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor);
        return interceptor;
    }

}

二、Mybatis-Plus帮助文档分析

Mybatis-Plus分页插件

在这里插入图片描述

  1. 参数page:为查询的结果集进行一个自动分页.换句话来说,就是指定查询出来的结果集怎么样显示。比如:返回的结果集要显示第1页的数据,并且每页显示10行 —> new Page(1,10)
  2. 编写一个普通的list查询:需求显示什么样的数据,你只需要给我一个list就行了。参数page会按照你的规则进行分页。
  3. 继承Page实现自己的分页对象:显示下一行、前一行等等这种功能,你就需要自己写一个分页对象规则。

总结:就是相当于你要自定义一个多表的复杂查询返回来一个list之后,通过你指定的page参数的分页规则,来进行分页

三、功能实现

目的:通过发起请求传过来的gender参数来分页查询。
要求:显示第1页的数据,且每页仅有2行

1. 总览目录结构

在这里插入图片描述

2. 代码编写

UserController.java

指定了显示第1页的数据,且每页仅有2行 new Page<>(1, 2)
编写了一个普通的list查询:selectUserByGender


使用了两种方法实现:

  1. 简单分页查询:用条件构造器QueryWrapper就能够实现
  2. 复杂分页查询:就必须自己手写mapper文件:联表查询
@RestController
public class UserController {

    @Autowired
    private UserService userService;
    
	 /**
     * <p>
     * 查询 : 根据gender性别查询用户列表,分页显示
     * </p>
     *
     * @param page 指定当前页码1 ,每页显示2行
     * @param state 状态
     * @return 分页对象
     */
    @RequestMapping("/{gender}")
    public void test(@PathVariable Integer gender) {
		// 模拟复杂分页查询
        IPage<UserEntity> userEntityIPage = userService.selectUserByGender(new Page<>(1, 2), gender);
        System.out.println("总页数: " + userEntityIPage.getPages());
        System.out.println("总记录数: " + userEntityIPage.getTotal());
        userEntityIPage.getRecords().forEach(System.out::println);
		// 简单分页查询
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("gender", gender);
        userService.pageByGender(new Page<>(1, 2), queryWrapper);
        System.out.println("总页数: " + userEntityIPage.getPages());
        System.out.println("总记录数: " + userEntityIPage.getTotal());
        userEntityIPage.getRecords().forEach(System.out::println);
    }
}
UserService.java

不涉及到啥复杂的处理,直接调用DAO层

@Service
public class UserService{

    @Autowired
    private UserMapper userMapper;

	// 模拟复杂分页查询
    public IPage<UserEntity> selectUserByGender(Page<UserEntity> page,Integer gender){
        return userMapper.selectUserByGender(page,gender);
    }
	
	// 简单分页查询:条件构造器QueryWrapper
    public IPage<UserEntity> pageByGender(Page<UserEntity> page, QueryWrapper<UserEntity> queryWrapper){
        return userMapper.selectPage(page,queryWrapper);
    }
}
UserMapper.java

官网说可以继承或者不继承BaseMapper。
我之所以实现是因为测试实现简单的分页查询:调用了条件构造器QueryWrapper里面的方法

@Mapper
public interface UserMapper extends BaseMapper<UserEntity> {

	// 通过性别分页查询
    IPage<UserEntity> selectUserByGender(Page<UserEntity> page, @Param("gender") Integer gender);
}
UserMapper.xml

根据官网的文档分析:根据需求查询编写一个list查询;
所以,我们就是需要自己写一个SQL语句查询 :根据gender输入的情况:显示用户列表

<?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="com.hyl.demo.mapper.UserMapper">
    <sql id = "entity">
        a.id,a.username,a.password,a.gender,a.age,a.create_time
    </sql>
    <select id="selectUserByGender" resultType="com.hyl.demo.entity.UserEntity">
        select <include refid="entity"/> from user a
        <where>
            <if test="gender != null">
                and a.gender = #{gender}
            </if>
        </where>
    </select>
</mapper>

3. 运行

执行了两次操作:

  1. 查询总行数
  2. 再进行SQL语句查询

http://localhost:9090/0
在这里插入图片描述

在这里插入图片描述

四、总结

第一个参数:

  • page:指定分页规则

第二个参数:

  • 复杂分页查询:自定义分页:编写SQL查询
  • 简单分页查询:条件构造器QueryWrapper

比较好的博客:
写的详细:ITKaven:MyBatis-Plus 之分页查询
写的很实用:致HTC:分页插件IPage

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐