后端分页查询的sql dao serice contoller 写法示例

SQL:
limit a,b
a 表示查询开始索引,从0开始
b表示查询的条数

limit 5,8表示查询从索引5开始的8条数据

<select id="listPage" resultMap="categoryMapper">
        select * from category
        <where>
            <if test="cateName!=null and cateName!=''">
                cateName like '%${cateName}%'
            </if>
            and deleted=0
        </where>
        limit #{page},#{size}
    </select>

DAO

这里的page含义其实不是页数,而是索引号

List<Category> listPage(@Param("page") int page,
                            @Param("size") int size,
                            @Param("cateName")String cateName);

Service

在Service的实现中进行页数到索引值的转换,即索引值=(页数减去1)*size

其实如果把dao和sql中的参数名改为fromindex 就比较好理解

@Override
    public List<Category> listPageCategory(int page, int size,String cateName) {
        return categoryDao.listPage((page-1)*size,size,cateName);
    }

Controller

Controller中的page就是页数

@RequestMapping("/listPage")
    public Map<String,Object>listPage(int page,int rows,String cateName){
        Map<String,Object> map=new HashMap<>();
        //统计分页记录数返回到页面中去,map的键不能随意写,前端表格规定的名称
        map.put("total",categoryService.countCategory(cateName));
        //结果及的map的键也是不能随意写,前端表格规定的名称
        map.put("rows",categoryService.listPageCategory(page,rows,cateName));
        return map;
    }
posted @ 2022-11-17 23:01  林动  阅读(4)  评论(0编辑  收藏  举报