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

相关推荐
干到60岁退休的码农3 天前
15.创建获取用户接口与JWT认证器
java·spring boot·mybatis
干到60岁退休的码农3 天前
16.过滤器中处理异常响应返回
java·spring boot·mybatis
敲代码的嘎仔4 天前
互动问答系统实战:两级评论模型、ES 搜索集成、Caffeine 多级缓存全记录
java·开发语言·数据库·elasticsearch·缓存·mybatis·高并发
无风听海5 天前
深入解析 Elasticsearch 的 match_phrase_prefix与 match_bool_prefix
大数据·elasticsearch·mybatis
摆烂z5 天前
定时任务同步数据--续跑&重试
java·mybatis·ai编程
Wang's Blog6 天前
Java框架快速入门: Spring Security+OAuth2之实现UserDetails与GrantedAuthority深度定制
java·spring·mybatis
阿维的博客日记7 天前
Example 类全场景实战指南
java·mybatis
阿维的博客日记8 天前
Example API指南2
java·mybatis
霸道流氓气质9 天前
MyBatis 与 SQL 层面关键技术详解
windows·sql·mybatis
₍˄·͈༝·͈˄*₎◞ ̑̑码10 天前
MyBatis操作数据库
数据库·mybatis