mybatis-plus 自定义sql拼接的方式进行Wrapper条件查询 实现了分页

法一:用单表的思想(可以跳过,直接看法二)

方法:先收集公共字段到集合中,再批量查询,然后封装起来

缺点:相较于法二,代码量大,多访问了一次数据库

service层:

@Service
@RequiredArgsConstructor
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {
    private final ICategoryService categoryService;
    @Override
    public List<ProductVO> searchList(ProductPageQueryDTO queryDTO) {
        // 根据分页查询
        Integer categoryId = queryDTO.getCategoryId();
        String title = queryDTO.getTitle();
        Page<Product> page = lambdaQuery()
                .eq(categoryId != null, Product::getCategoryId, categoryId)
                .like(!StrUtil.isBlank(title), Product::getTitle, title)
                .page(Page.of(queryDTO.getPageNum(), queryDTO.getPageSize()));
        List<Product> records = page.getRecords();

        // 获取商品分类名称
        List<Integer> categoryIds = new ArrayList<>(records.size());
        for (Product record : records) {
            categoryIds.add(record.getCategoryId());
        }
        Map<Integer, String> namesMap = categoryService.getNamesByIds(categoryIds);
        System.out.println(namesMap.get(1));

        // 封装结果
        List<ProductVO> productVOS = BeanUtil.copyToList(records, ProductVO.class);
        for (ProductVO productVO : productVOS) {
            String categoryName = namesMap.get(productVO.getCategoryId());
            productVO.setCategoryName(categoryName);
        }
        return productVOS;
    }
}
@Service
@RequiredArgsConstructor
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {
    private final CategoryMapper categoryMapper;
    

    @Override
    public Map<Integer, String> getNamesByIds(List<Integer> categoryIds) {
        return categoryMapper.getNamesByIds(categoryIds);
    }



}

Mapper层:

public interface CategoryMapper extends BaseMapper<Category> {
    @MapKey("id")
    Map<Integer, String> getNamesByIds(List<Integer> categoryIds);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ptu.mall.mapper.CategoryMapper">

    <select id="getNamesByIds" resultType="map">
        select name
        from category
        where id in
        <foreach collection="categoryIds" item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </select>

</mapper>

法二:

方法:自定义sql拼接mp查询条件

解释:mybatis-plus只要配置了分页插件,当Page进入mapper层时,就会进行分页的sql拼接

Service

@Service
@RequiredArgsConstructor
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {
    private final ProductMapper productMapper;
    @Override
    public List<ProductVO> searchListGood(ProductPageQueryDTO queryDTO) {
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        Integer categoryId = queryDTO.getCategoryId();
        String title = queryDTO.getTitle();
        wrapper.eq(categoryId != null, Product::getCategoryId, categoryId).
                like(!StrUtil.isBlank(title), Product::getTitle, title);
        Page<ProductVO> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        return productMapper.pageQuery(page, wrapper);
    }
}

mapper

public interface ProductMapper extends BaseMapper<Product> {
    List<ProductVO> pageQuery(Page<ProductVO> page, @Param("ew") LambdaQueryWrapper<Product> wrapper);
}

xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ptu.mall.mapper.ProductMapper">

    <select id="pageQuery" resultType="com.ptu.mall.domain.vo.ProductVO">
        select p.id as id, p.code as code, p.title as title, p.category_id as categoryId, c.name as categoryName, p.img as img, p.price as price, p.stocks as stocks, p.description as description
        from product p
        left join category c on p.category_id = c.id
        ${ew.customSqlSegment}

    </select>
</mapper>

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis-Plus是MyBatis的增强工具,在分页方面也提供了更加便捷的操作。MyBatis-Plus的分页查询使用PageHelper类实现,只需要将Page对象作为参数传入查询方法中即可。 以下是使用MyBatis-Plus进行分页查询的示例代码: ```java // 创建分页对象 Page<User> page = new Page<>(pageNum, pageSize); // 执行分页查询 IPage<User> userPage = userDao.selectPage(page, new QueryWrapper<User>()); // 获取分页查询结果 List<User> userList = userPage.getRecords(); long total = userPage.getTotal(); ``` 其中,`userDao`是MyBatis的Mapper接口,`selectPage`方法是MyBatis-Plus提供的分页查询方法,`new QueryWrapper<User>()`则是MyBatis-Plus提供的查询条件封装类。在查询结果中,`userList`是当前页的数据列表,`total`则是总记录数。 需要注意的是,分页查询方法需要在Mapper接口中定义,如下所示: ```java public interface UserDao extends BaseMapper<User> { IPage<User> selectUserPage(Page<User> page, @Param("ew") QueryWrapper<User> wrapper); } ``` 在XML文件中,需要使用`<select>`标签定义分页查询方法,如下所示: ```xml <select id="selectUserPage" parameterType="com.baomidou.mybatisplus.extension.plugins.pagination.Page" resultMap="userMap"> select * from user <where> <if test="ew!=null"> <if test="ew.sqlSegment != null and ew.sqlSegment != ''"> ${ew.sqlSegment} </if> </if> </where> </select> ``` 其中,`parameterType`指定了分页对象的类型,`resultMap`则是查询结果的映射。在SQL语句中,需要使用`<if>`标签判断查询条件是否存在,使用`${ew.sqlSegment}`将查询条件拼接SQL语句中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值