Mybatis-plus自定义连表分页查询

上一篇文章简单示范自定义分页查询,可通过QueryWrapper自由添加条件查询。也可以在xml中自定义sql语句。

复杂的自定义连表分页查询,就不是那么随意了。

ProductServiceImpl.java

    @Override
    public IPage<Product> querySpu(ProductQueryItems items) {
        int page = items.getPage() == null ? 1 : items.getPage();
        int pagesize = items.getPagesize() == null ? 20 : items.getPagesize();
        Page<Product> page1 = new Page<>(page, pagesize);
        QueryWrapper<Product> wrapper = new QueryWrapper<Product>();
        if(items.getCode() != null) wrapper.like("code", items.getCode());
        if(items.getName() != null) 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是如何定义的:
Mybatis-plus自定义连表分页查询_第1张图片

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

所以,为了匹配别名,手动加上xml中定义的别名即可
Mybatis-plus自定义连表分页查询_第2张图片

你可能感兴趣的:(Mybatis-Plus)