解决Mybatis-Plus或PageHelper多表分页查询总条数不对问题

前言

项目老大说项目需要重构搜索功能,决定交给我这个比较闲的人! 嗯 ???

因为以前的项目数据不大,都不能说不大,是很少,所有搜索采用的是MySQL中的like模糊搜索操作的,他希望我改一下;

我第一时间想到了ES,但他说没必要用ES,等以后数据量大了再换,现在只是稍微多了一些数据,没必要

Ok!那我就用了MySQL自带的全文检索功能,因为本文主要说的还是Mybatis-Plus的问题,所以全文检索在下面只会提到怎么使用,以及一些问题

好像说了一大堆废话,回归正题!

项目以前分页搜索用的是PageHelper这个插件,但公司封装的3.0框架中已经封装了Mybatis-Plus,所以我采用了Mybatis-Plus的分页插件

一、问题说明

场景:

老师表是有4条数据,每个老师对应2个学生

使用的是两个表联查letf joinMybatis的级联查询,一次性获取所有数据出现3个问题:

1、数据总条数以及页数不对

2、数据分页数量不对

3、数据混乱

已下是我有问题的代码:

1、引入依赖

版本选择尽量3.4+

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

2、Mybatis-Plus配置

@Configuration
public class MybatisPlusConfig {

    /**
     * 插件注册
     *
     * @param paginationInnerInterceptor 分页插件
     * @return MybatisPlus拦截器
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(PaginationInnerInterceptor paginationInnerInterceptor) {
        MybatisPlusInterceptor mp = new MybatisPlusInterceptor();
        mp.addInnerInterceptor(paginationInnerInterceptor);
        return mp;
    }

    //分页插件
    @Bean
    public PaginationInnerInterceptor paginationInnerInterceptor() {
        PaginationInnerInterceptor pii = new PaginationInnerInterceptor();
        pii.setMaxLimit(20L);
        pii.setDbType(DbType.MYSQL);
        //当超过最大页数时不会报错
        pii.setOverflow(true);
        return pii;
    }

}

3、创建mapper层

创建了一个返回实体类TeacherVO,包括老师信息以及学生信息,以及一个传入的参数类TeacherRequestVo

@Data
public class TeacherVO {
     /**
     * 跟学生表关联的字段
     */
    private String classs;

    private String tname;

    private String tsex;

    private Date tbirthday;

    private String prof;

    private String depart;

    private List<Student> student;
}
@Data
public class TeacherRequestVo {
    private String classs;
    private String tname;
    private String sname;
}
public interface TeacherMapper extends BaseMapper<Teacher> {
    /**
     * 获取老师所带班级中的所有老师及学生信息
     * @param page mybatisplus自带的page类
     * @param teacherRequestVo 传入的参数
     * @return
     */
    Page<TeacherVO> getAll(Page<TeacherVO> page, TeacherRequestVo teacherRequestVo);
}

4、编写xxxMapper.xml文件

<resultMap id="GetAllMap" type="com.qjj.demo.entity.vo.TeacherVO">
    <!--@mbg.generated-->
    <!--@Table teacher-->
    <result column="classs" jdbcType="VARCHAR" property="classs"/>
    <result column="Tname" jdbcType="VARCHAR" property="tname"/>
    <result column="Tsex" jdbcType="VARCHAR" property="tsex"/>
    <result column="Tbirthday" jdbcType="TIMESTAMP" property="tbirthday"/>
    <result column="Prof" jdbcType="VARCHAR" property="prof"/>
    <result column="Depart" jdbcType="VARCHAR" property="depart"/>
    <collection property="student"
                ofType="com.qjj.demo.entity.Student"
                resultMap="com.qjj.consumer.mapper.StudentMapper.BaseResultMap"/>
</resultMap>

<select id="getAll" resultMap="GetAllMap">
    select *
    from teacher t
    left join student s on t.classs = s.classs
    <where>
        <if test="param2.size != null">
            and s.size <![CDATA[ <= ]]> #{param2.size}
        </if>
        <if test="param2.classs != null and param2.classs != ''">
            and t.classs = #{param2.classs}
        </if>
        <if test="param2.sname != null and param2.sname != ''">
            and s.Sname = #{param2.sname}
        </if>
        <if test="param2.tname != null and param2.tname != ''">
            and t.Tname = #{param2.tname}
        </if>
    </where>
</select>

5、测试一(不传任何条件,只分页)

测试结果应该是二条数据,总数是四条

@RestController
@RequestMapping("/demo")
public class DemoController {

    @Resource
    private TeacherMapper teacherMapper;


    @PostMapping("/test3")
    public Page<TeacherVO> getAll(TeacherRequestVo teacherRequestVo) {
        Page<TeacherVO> teacherVOPage = new Page<>(1, 2);
        return teacherMapper.getAll(teacherVOPage, teacherRequestVo);
    }

}

在这里插入图片描述

{
    "records": [
        {
            "classs": "804",
            "tname": "李诚",
            "tsex": "男",
            "tbirthday": "1958-12-02 00:00:00",
            "prof": "副教授",
            "depart": "计算机系",
            "student": [
                {
                    "sno": "108",
                    "sname": "丘东",
                    "ssex": "男",
                    "sbirthday": "1977-09-01 00:00:00",
                    "classs": null
                },
                {
                    "sno": "105",
                    "sname": "匡明",
                    "ssex": "男",
                    "sbirthday": "1975-10-02 00:00:00",
                    "classs": null
                }
            ]
        }
    ],
    "total": 4,
    "size": 2,
    "current": 1,
    "orders": [],
    "optimizeCountSql": true,
    "searchCount": true,
    "countId": null,
    "maxLimit": null,
    "pages": 2
}
5.1、结果总结

1、总条数正确

2、页数正确

3、数据不正确,返回条数不正确,应该返回两条数据,但现在只返回了一条

5.2、结果分析

查看它最终指向的sql语句

找到在SimpleExecutor下的doQuery方法。

在这里插入图片描述

总条数的sql语句为:

SELECT COUNT(*) AS total FROM teacher t

分页语句为:

select *
   from teacher t
       left join student s on t.classs = s.classs LIMIT 2

拿去数据库运行结果为:

在这里插入图片描述

至此可以看出它只是获取了同一个老师下两个不同的学生信息

而不是我们想象的两个老师,分别对应多个学生;

但总条数和条数正确

6、测试二(传两个表的条件)

在这里插入图片描述

得到的结果应该是一个老师对应他下面的两个学生

总条数是1

总数是1

6.1、测试结果
{
    "records": [
        {
            "classs": "804",
            "tname": "李诚",
            "tsex": "男",
            "tbirthday": "1958-12-02 00:00:00",
            "prof": "副教授",
            "depart": "计算机系",
            "student": [
                {
                    "sno": "108",
                    "sname": "丘东",
                    "ssex": "男",
                    "sbirthday": "1977-09-01 00:00:00",
                    "classs": null,
                    "size": 1
                },
                {
                    "sno": "105",
                    "sname": "匡明",
                    "ssex": "男",
                    "sbirthday": "1975-10-02 00:00:00",
                    "classs": null,
                    "size": 2
                }
            ]
        }
    ],
    "total": 2,
    "size": 2,
    "current": 1,
    "orders": [],
    "optimizeCountSql": true,
    "searchCount": true,
    "countId": null,
    "maxLimit": null,
    "pages": 1
}
6.2、结果总结

总条数不对

页数虽然对,但是那是因为我们分页的数量是2,而学生表中正好是一个老师对应两个学生,所以才对,但只要当一个老师对应3个学生或者超过2的话,页数也就不会对了,这里就不给大家测试了,大家可以自行测试一下

数据虽然看起来对的,但是跟页数是一样的道理,其实是错的

6.3、结果分析

还是查看它最终执行的SQL语句:

发现执行查询总条数的SQL语句有问题

SELECT COUNT(*) AS total FROM teacher t LEFT JOIN student s ON t.classs = s.classs WHERE s.size <= 3 AND t.classs = '804'

二、解决

在上面的测试中发现两个问题

1、数据不对

2、条数和页数不对

1、没条件查询只分页

我们修改xxxMapper.xml中的resultMap采用级联查询

  <resultMap id="GetAllMap" type="com.qjj.demo.entity.vo.TeacherVO">
        <!--@mbg.generated-->
        <!--@Table teacher-->
        <result column="classs" jdbcType="VARCHAR" property="classs"/>
        <result column="Tname" jdbcType="VARCHAR" property="tname"/>
        <result column="Tsex" jdbcType="VARCHAR" property="tsex"/>
        <result column="Tbirthday" jdbcType="TIMESTAMP" property="tbirthday"/>
        <result column="Prof" jdbcType="VARCHAR" property="prof"/>
        <result column="Depart" jdbcType="VARCHAR" property="depart"/>
        <collection property="student"
                    ofType="com.qjj.demo.entity.Student1"
                    column="classs"
                    select="getStudent"/>
    </resultMap>
    <select id="getAll" resultMap="GetAllMap">
        select t.*
        from teacher t
                     left join student s on t.classs = s.classs
        <where>
            <if test="param2.size != null">
                and s.size <![CDATA[ <= ]]> #{param2.size}
            </if>
            <if test="param2.classs != null and param2.classs != ''">
                and t.classs = #{param2.classs}
            </if>
            <if test="param2.sname != null and param2.sname != ''">
                and s.Sname = #{param2.sname}
            </if>
            <if test="param2.tname != null and param2.tname != ''">
                and t.Tname = #{param2.tname}
            </if>
        </where>
    </select>
    
    <select id="getStudent" resultMap="com.qjj.demo.mapper.Student1Mapper.BaseResultMap">
        select *
        from student
        where classs = #{classs}
    </select>

在这里插入图片描述

{
    "records": [
        {
            "classs": "804",
            "tname": "李诚",
            "tsex": "男",
            "tbirthday": "1958-12-02 00:00:00",
            "prof": "副教授",
            "depart": "计算机系",
            "student": [
                {
                    "sno": "108",
                    "sname": "丘东",
                    "ssex": "男",
                    "sbirthday": "1977-09-01 00:00:00",
                    "classs": null,
                    "size": 1
                },
                {
                    "sno": "105",
                    "sname": "匡明",
                    "ssex": "男",
                    "sbirthday": "1975-10-02 00:00:00",
                    "classs": null,
                    "size": 2
                }
            ]
        },
        {
            "classs": "804",
            "tname": "李诚",
            "tsex": "男",
            "tbirthday": "1958-12-02 00:00:00",
            "prof": "副教授",
            "depart": "计算机系",
            "student": [
                {
                    "sno": "108",
                    "sname": "丘东",
                    "ssex": "男",
                    "sbirthday": "1977-09-01 00:00:00",
                    "classs": null,
                    "size": 1
                },
                {
                    "sno": "105",
                    "sname": "匡明",
                    "ssex": "男",
                    "sbirthday": "1975-10-02 00:00:00",
                    "classs": null,
                    "size": 2
                }
            ]
        }
    ],
    "total": 4,
    "size": 2,
    "current": 1,
    "orders": [],
    "optimizeCountSql": true,
    "searchCount": true,
    "countId": null,
    "maxLimit": null,
    "pages": 2
}

2、两个表都有条件

在这里插入图片描述

{
    "records": [
        {
            "classs": "804",
            "tname": "李诚",
            "tsex": "男",
            "tbirthday": "1958-12-02 00:00:00",
            "prof": "副教授",
            "depart": "计算机系",
            "student": [
                {
                    "sno": "108",
                    "sname": "丘东",
                    "ssex": "男",
                    "sbirthday": "1977-09-01 00:00:00",
                    "classs": null,
                    "size": 1
                },
                {
                    "sno": "105",
                    "sname": "匡明",
                    "ssex": "男",
                    "sbirthday": "1975-10-02 00:00:00",
                    "classs": null,
                    "size": 2
                }
            ]
        },
        {
            "classs": "804",
            "tname": "李诚",
            "tsex": "男",
            "tbirthday": "1958-12-02 00:00:00",
            "prof": "副教授",
            "depart": "计算机系",
            "student": [
                {
                    "sno": "108",
                    "sname": "丘东",
                    "ssex": "男",
                    "sbirthday": "1977-09-01 00:00:00",
                    "classs": null,
                    "size": 1
                },
                {
                    "sno": "105",
                    "sname": "匡明",
                    "ssex": "男",
                    "sbirthday": "1975-10-02 00:00:00",
                    "classs": null,
                    "size": 2
                }
            ]
        }
    ],
    "total": 2,
    "size": 2,
    "current": 1,
    "orders": [],
    "optimizeCountSql": true,
    "searchCount": true,
    "countId": null,
    "maxLimit": null,
    "pages": 1
}

3、结果总结

  1. 无条件时

    数量正确,数据重复,页数正确

  2. 两表都有条件时:

    总数不对,数据重复,页数不正确

4、结果分析

查看最终sql语句

查询总条数的SQL语句:

SELECT COUNT(*) AS total FROM teacher t LEFT JOIN student s ON t.classs = s.classs WHERE s.size <= ? AND t.classs = ?

查询老师表的SQL语句:

  select t.*
        from teacher t
              left join student s on t.classs = s.classs
        WHERE s.size  <= 3
        and t.classs = "804" LIMIT 2

去数据库执行发现查询老师表的sql语句查出两条相同结果

其实到这里很多人都知道怎么解决了,只要去除重复的数据,所有问题都可以解决,无论是用去重,还是GROUP BY都可以实现,我下面采用GROUP BY

5、最终方案

加上GROUP BY进行去重,其他地方都没改动

 <select id="getAll" resultMap="GetAllMap">
        select t.classs,
               t.Tname,
               t.Tsex,
               t.Tbirthday,
               t.Prof,
               t.Depart
        from teacher t
                     left join student s on t.classs = s.classs
        <where>
            <if test="param2.size != null">
                and s.size <![CDATA[ <= ]]> #{param2.size}
            </if>
            <if test="param2.classs != null and param2.classs != ''">
                and t.classs = #{param2.classs}
            </if>
            <if test="param2.sname != null and param2.sname != ''">
                and s.Sname = #{param2.sname}
            </if>
            <if test="param2.tname != null and param2.tname != ''">
                and t.Tname = #{param2.tname}
            </if>
        </where>
        GROUP BY t.classs
    </select>
5.1、坑

进行分组的字段必须是主键或者是唯一索引,不然会报错,原因只有一点:

我们可以去MySQL的官网查看,会有说明,在MySQL5.75以后的版本查询的字段,在进行分组的时候,都要出现在group by后面,以及当group by 后面跟上主键或者不为空唯一索引时,查询是有效的,因为此时的每一行数据都具有唯一性。

这里就不给大家展示测试结果了,没必要了,大家可自行测试

到这里问题完美解决

三、结束语

本人写过的所有解决什么问题都是项目中花了超过1个多小时才解决的问题,希望这篇文章对同学们有所帮助,不喜勿喷,有任何问题都可以评论,最后送上我的两句座右铭:

任何人都不会在意你成功的过程,只在意你成功的结果,在你没有成功之前,切勿向别人强调过程;

请不要假装努力,结果不会陪你演戏;

  • 11
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 14
    评论
### 回答1: Mybatis-plus 可以很方便地与 PageHelper 整合,实现分页查询功能。 具体步骤如下: 1. 引入 PageHelperMybatis-plus 的依赖。 2. 在 Mybatis-plus 的配置文件中,配置分页插件: ``` <!-- 分页插件 --> <bean id="paginationInterceptor" class="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"> <property name="dialectType" value="mysql"/> </bean> ``` 3. 在需要分页的方法中,使用 PageHelper.startPage 方法设置分页参数: ``` PageHelper.startPage(pageNum, pageSize); List<User> userList = userMapper.selectList(null); ``` 其中,pageNum 表示当前页码,pageSize 表示每页显示的记录数。 4. 将查询结果封装成 PageInfo 对象,返回给前端: ``` PageInfo<User> pageInfo = new PageInfo<>(userList); return Result.success(pageInfo); ``` 这样,就可以实现基于 Mybatis-plusPageHelper分页查询功能了。 ### 回答2: Mybatis-plus 是一款优秀的 Mybatis 增强工具,在它的基础上整合 PageHelper 可以方便进行分页查询操作,下面介绍具体的整合步骤。 1. 添加依赖 首先,在 Maven 中添加 Mybatis-plusPageHelper 的依赖: ``` <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>{latest-version}</version> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>{latest-version}</version> </dependency> ``` 其中的最新版本可以在 Maven 中央库中查找。 2. 配置 PageHelper 在 Spring Boot 的配置文件 application.yml 中进行配置: ``` pagehelper: helperDialect: mysql reasonable: true supportMethodsArguments: true params: count=countSql ``` 这里设置了数据库方言为 MySQL,reasonable 属性设置为 true 表示启用合理化分页,supportMethodsArguments 属性为 true 表示支持通过方法参数传入分页信息,params 属性为 count=countSql 表示分页插件会自动统计数。 3. 使用 PageHelper 进行分页查询 在需要分页查询的接口方法中,使用 PageHelper.startPage 方法进行分页操作: ``` @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public PageInfo<User> getUsers(int pageNum, int pageSize) { PageHelper.startPage(pageNum, pageSize); List<User> userList = userMapper.selectList(null); return new PageInfo<>(userList); } } ``` 这里的 pageNum 和 pageSize 分别表示当前页数和每页记录数,PageHelper 会自动根据这两个参数进行分页查询操作,返回的 PageInfo 对象包含分页信息以及查询结果。注意,需要将 Mybatis-plus 的查询结果转换为 List 类型,才能进行分页操作。 通过以上操作,就可以很方便地整合 Mybatis-plusPageHelper 进行分页查询了。 ### 回答3: MyBatis-Plus 是在 MyBatis 基础上的增强工具,提供了很多方便开发的功能,例如快速开发 CRUD,自动分页,租户隔离等。而显示分页数据是 Web 应用程序中经常使用的功能。为了在 MyBatis-Plus 中实现分页功能,我们可以使用 PageHelper 插件。 PageHelper 是一个 MyBatis 物理分页插件,它生成适合多种数据库的分页查询 SQL 语句,使用 PageHelper 对 SQL 语句增加了分页语句,用于显示分页查询结果。 在使用 MyBatis-Plus 整合 PageHelper 时,我们需要进行以下几个步骤: 1. 引入依赖 在 pom.xml 文件中引入 MyBatis-PlusPageHelper 的依赖: ``` <!-- MyBatis-Plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.x.x</version> </dependency> <!-- PageHelper --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.3.x</version> </dependency> ``` 2. 配置分页插件 在 MyBatis 配置文件中增加如下分页插件的配置: ``` <plugins> <!-- 分页插件 --> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <property name="dialect" value="mysql"/> <property name="reasonable" value="true"/> </plugin> </plugins> ``` 此处使用的是 PageInterceptor,是 PageHelper 的核心插件。 其中,dialect 属性决定了使用哪种数据库语言;reasonable 属性决定是否开启分页合理化。 3. 代码实现分页查询 在使用 MyBatis-Plus 进行查询时,结合 PageHelper 插件实现分页查询: ``` Page<User> page = new Page<>(1, 10); // 查询第 1 页,每页 10 条记录 IPage<User> userIPage = userService.page(page, new QueryWrapper<User>().lambda().eq(User::getGender, 1)); List<User> userList = userIPage.getRecords(); ``` 其中,page 对象作为分页查询的参数,包含了当前页码以及每页的记录数;userService.page() 方法是 MyBatis-Plus 提供的分页查询方法,第一个参数是 page 对象,第二个参数是查询条件。 4. 前端展示分页数据 在前端页面中使用分页插件进行数据的展示,PageHelper 提供了 Page 对象中 pageList 属性,可以直接获取分页后的数据集合: ``` <% List<User> userList = (List<User>) request.getAttribute("userList"); %> <table class="table table-bordered"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Gender</th> <th>Age</th> </tr> </thead> <tbody> <% for (User user : userList) { %> <tr> <td><%= user.getId() %></td> <td><%= user.getName() %></td> <td><%= user.getGender() %></td> <td><%= user.getAge() %></td> </tr> <% } %> </tbody> </table> <div class="text-center"> <% out.print(new Paging(request.getRequestURI()).getHtml(); %> </div> ``` 其中,Paging 是一个辅助类,用于展示分页条。 通过使用 MyBatis-Plus 整合 PageHelper 插件,我们可以轻松地实现分页查询功能,并且在前端页面中展示分页数据。这样,我们就可以提高数据查询的效率,同时也让用户对数据更加清晰明了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值