使用 mybatis-plus 的mybaits的一对多时, total和record的不匹配问题

应该是框架的问题,去官方仓库提了个issues,等回复

https://github.com/baomidou/mybatis-plus/issues/5923

回复来了:

背景

发现 record是两条,但是total显示3

使用resultMap一对多时,三条数据会变成两条,但是total确是3条

下面是一对多的resultMap代码

想要达成的效果

有意思的是,把sql拿出来,执行的确是三条,只是在mapper中进行了一对多的关联,关联后变成两条

但是这里的total有问题,需要优化

原理分析

mybatis-plus在执行sql前,会执行查询total的sql

这里的查询是根据原sql拼接而来,也就是未进行一对多操作的sql

怀疑是框架本身的bug,在框架项目的issues中查找了一番,并没有找到相关答案

框架地址:https://github.com/baomidou/mybatis-plus

于是选择更换一对多的方式,改为子查询

改动前:

<collection property="potentialCustomerMediaVOList" ofType="com.djbx.cxb.manager.vo.business.PotentialCustomerMediaVO">
    <result column="create_time" property="createTime"/>
    <result column="url" property="url"/>
</collection>

改动后:

<collection property="potentialCustomerMediaVOList" ofType="com.djbx.cxb.manager.vo.business.PotentialCustomerMediaVO" select="getCustomerMediaVOList"
            column="id">
    <id column="id" property="id"/>
    <result column="create_time" property="createTime"/>
    <result column="url" property="url"/>
</collection>

子查询sql:

<select id="getCustomerMediaVOList" resultType="com.djbx.cxb.manager.vo.business.PotentialCustomerMediaVO">
    select pcm.id, pcm.create_time, pcm.url from potential_customer_media pcm where pcm.pid = #{id} and pcm.media_node = 3
    order by pcm.id desc
</select>

完美解决!又捡起来一种遗忘的mybatis一对多的方式

引申思考

如何传入前端入参到子查询中?

可以在父查询中新增一个查询字段,比如:select #{param.address} as address

然后在column中传入

<collection property="potentialCustomerMediaVOList" ofType="com.djbx.cxb.manager.vo.business.PotentialCustomerMediaVO" select="getCustomerMediaVOList"
            column="id">
    <id column="{id=id,address=address}" property="id"/>
    <result column="create_time" property="createTime"/>
    <result column="url" property="url"/>
</collection>

未测试,应该可用

参考链接

Mybatis一对多,分页问题及映射问题_一对多映射 分页-CSDN博客

相关推荐
Flying_Fish_roe2 小时前
MyBatis-Plus 常见问题与优化
java·tomcat·mybatis
终末圆5 小时前
MyBatis XML映射文件编写【后端 18】
xml·java·开发语言·后端·算法·spring·mybatis
kunkun1015 小时前
Mybatis的XML实现方法
xml·java·mybatis
码农小伙5 小时前
SpringBoot中基于Mybatis-Plus多表联查(无xml,通过注解实现)
xml·spring boot·mybatis
aloha_78919 小时前
B站宋红康JAVA基础视频教程(chapter14数据结构与集合源码)
java·数据结构·spring boot·算法·spring cloud·mybatis
狼爷20 小时前
SpringBoot整合MyBatis-Plus
java·mybatis
coffee_baby1 天前
享元模式详解:解锁高效资源管理的终极武器
java·spring boot·mybatis·享元模式
程序员大金1 天前
基于SSM+Vue+MySQL的酒店管理系统
前端·vue.js·后端·mysql·spring·tomcat·mybatis
Tatakai252 天前
Mybatis Plus分页查询返回total为0问题
java·spring·bug·mybatis
A_cot2 天前
Redis 的三个并发问题及解决方案(面试题)
java·开发语言·数据库·redis·mybatis