实例:MyBatis-Plus自定义联表分页查询

系列文章目录

第一篇:实例:MyBatis-Plus自定义分页查询
第二篇:实例:MyBatis-Plus自定义联表分页查询
第三篇:实例:MyBatis-Plus自定义联表分页查询-动态sql实现



上一篇文章简单示范自定义分页查询,可通过QueryWrapper自由添加条件查询。也可以在xml中自定义sql语句。
复杂的自定义连表分页查询,就不是那么随意了。
此篇文章的做法已被本人弃用,更简洁规范的做法可以参考此系列文章第三篇。

一、关键代码

  • ProductServiceImpl.java
    @Override
    public IPage<Product> querySpu(ProductQueryItems items) {
        Page<Product> page1 = new Page<>(items.getPage(), items.getPagesize());
        QueryWrapper<Product> wrapper = new QueryWrapper<Product>();
        if(items.getCode() != null && items.getCode().trim() != "") wrapper.like("code", items.getCode());
        if(items.getName() != null && items.getName().trim() != "") wrapper.like("name", items.getName());
        if(items.getStartCreateTime() != null && items.getEndCreateTime() != null) {
            wrapper.between("create_time", items.getStartCreateTime(), items.getEndCreateTime());
        }
        IPage<Product> mapIPage = productMapper.selectPageSpu(items.getCatalogId(), page1, wrapper);
        return mapIPage;
    }
  • ProductMapper.java
public interface ProductMapper extends BaseMapper<Product> {

	IPage<Product> selectPageSpu(@Param("cid") Long catalogId, IPage<Product> page,
		@Param(Constants.WRAPPER) Wrapper<Product> queryWrapper);
}

  • ProductMapper.xml
<select id="selectPageSpu" resultType="Product">
    SELECT p.* FROM pd.pd_product p
        inner join pd.pd_product_catalog pc
            on p.id=pc.product_id and pc.delete_time isnull
            inner join pd.pd_catalog c
                on pc.catalog_id=c.id and c.id=#{cid} and c.delete_time isnull
    ${ew.customSqlSegment}
</select>

customSqlSegment中,我们添加了对name,code的查询,但此时会报错,表示name,code指代模糊。

org.postgresql.util.PSQLException: ERROR: column reference “name” is ambiguous

即,sql中所需的是
WHERE p.name LIKE ? AND p.code LIKE ?
再看看,我们的customSqlSegment是如何定义的:
在这里插入图片描述

而,${ew.customSqlSegment}给我们拼接的实际上是
WHERE name LIKE ? AND code LIKE ?

所以,为了匹配别名,手动加上xml中定义的别名即可
在这里插入图片描述

二、总结

上述做法虽然也能达成目标,不过不够规范,代码繁琐。通过学习mybatis的动态sql后,发现完全可以用它来实现联表的分页查询。


MyBatis相关教程:
MyBatis教程
MyBatis-Plus官方文档

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值