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

相关推荐
一嘴一个橘子1 天前
mybatis - 多表映射(对一映射、对多映射)
java·mybatis
子沫20202 天前
使用mybatis-plus、mybatis插入数据库时加密,查询数据库时解密,自定义TypeHandler 加解密使用
数据库·mybatis·mybatis-plus
w***76552 天前
存储技术全景:从基础原理到未来趋势
spring boot·后端·mybatis
醇氧2 天前
SqlLogInterceptor mybatis配置打印SQL
java·sql·mybatis
符哥20082 天前
Mybatis和Mybatis-plus区别
java·开发语言·mybatis
二哈喇子!2 天前
基于SSM框架的网上商城购物系统的设计与实现(开源项目——实现CRUD功能整体流程超详细)
java·spring·mybatis·ssm
惊讶的猫2 天前
nia500总结
java·spring·mybatis
Nonoas2 天前
【Java】MyBatis源码学习大纲
java·学习·mybatis
二哈喇子!2 天前
SpringBoot启动失败Application run failed的解决办法
java·spring boot·mybatis
二哈喇子!2 天前
IDEA启动后控制台不报错,但是页面访问404
java·intellij-idea·mybatis