系列文章目录
第一篇:实例: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官方文档