使用 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博客

相关推荐
kkkkk0211061 天前
微服务学习笔记(黑马商城)
java·spring boot·spring·spring cloud·sentinel·mybatis·java-rabbitmq
夜幽青玄1 天前
mybatis-plus调用报 org.springframework.dao.DataIntegrityViolationException 错误处理
开发语言·python·mybatis
毕业设计制作和分享2 天前
springboot150基于springboot的贸易行业crm系统
java·vue.js·spring boot·后端·毕业设计·mybatis
SpiderPex2 天前
论MyBatis和JPA权威性
java·mybatis
瑞士卷@2 天前
MyBatis入门到精通(Mybatis学习笔记)
java·数据库·后端·mybatis
optimistic_chen2 天前
【Java EE进阶 --- SpringBoot】Mybatis - plus 操作数据库
数据库·spring boot·笔记·java-ee·mybatis·mybatis-plus
詩句☾⋆᭄南笙2 天前
Mybatis一对一、一对多
java·mybatis·resulttype·resultmap·一对多·一对一
DokiDoki之父3 天前
MyBatis—增删查改操作
java·spring boot·mybatis
DokiDoki之父3 天前
Mybatis—入门 & (配置)SQL提示和日志输出
数据库·sql·mybatis
计算机学姐5 天前
基于微信小程序的垃圾分类管理系统【2026最新】
java·vue.js·spring boot·mysql·微信小程序·小程序·mybatis