mybatis配合pagehelper分页助手查询

Maven:

在pom.xml中配置依赖:

        <!-- 分页助手启动器 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.6</version>
        </dependency>

service中使用:

/**
     * 根据查询条件分页并排序查询品牌信息
     * @param key
     * @param page
     * @param rows
     * @param sortBy
     * @param desc
     * @return
     */
    public PageResult<Brand> queryBrandsByPage(String key, Integer page, Integer rows, String sortBy, Boolean desc) {

        // 初始化example对象
        Example example = new Example(Brand.class);
        Example.Criteria criteria = example.createCriteria();

        // 根据name模糊查询,或者根据首字母查询
        if (StringUtils.isNotBlank(key)) {
            criteria.andLike("name","%" + key + "%").orEqualTo("letter",key);
        }

        // 添加分页条件
        PageHelper.startPage(page,rows);

        // 添加排序条件
        if (StringUtils.isNotBlank(sortBy)) {
            // 通过判断desc是true还是false,确定升序还是降序
            example.setOrderByClause(sortBy + " " + (desc ? "desc" : "asc"));   // 相当于“id desc”
        }

        // 将查询到的结果保存在Brand类型的list中
        List<Brand> brands = this.brandMapper.selectByExample(example);

        // 包装成pageInfo
        PageInfo<Brand> pageInfo = new PageInfo<>(brands);

        // 包装成分页的结果集返回
        return new PageResult<>(pageInfo.getTotal(),pageInfo.getList());

    }

猜你喜欢

转载自www.cnblogs.com/flypig666/p/11732710.html