1. 程式人生 > 其它 >用limit 實現java的簡單分頁

用limit 實現java的簡單分頁

技術標籤:部落格mysql

https://blog.csdn.net/xinyuezitang/article/details/84324359

用limit 實現java的簡單分頁

xinyuezitang2018-11-21 16:01:134447收藏9

分類專欄:Java 小Demo文章標籤:分頁limitmysql實現java分頁

版權

一 mysql 中limit 用法

select * from table limit m,n       
意思是: 在table資料庫中, 從m開始,拉取n條資料.

在mysql中, m代表index, 預設從0 開始;   n最小從m+1開始,取n條
limit start,size           從start條開始,獲取size條資料

二 分頁實現

前端思路:

將page 和 rows 兩個引數傳遞給後端	
page : 代表第幾頁
rows:  代表當前頁顯示的資料條數

java思路:

獲取當前頁的第一條:          (page-1)*rows	
sql語句查詢分頁: 	        limit (page-1)*rows,rows
sql語句獲取列表總數量:       select count(1) from table

三 後端程式碼:

Controller:

	@Autowired
    private ActivityService activityService;
    	
	@RequestMapping("/url")
    public ResponseEntity<?> getRecords(@RequestParam("uid") String uid,
                                            @RequestParam(value="page",required = false, defaultValue ="1") int page,
                                            @RequestParam(value="rows",required = false, defaultValue ="10") int rows){ 
        List<MyRecord> records = activityService.getMyRecord(uid,page,rows);
        Long  total = activityService.getMyRecordCount(uid);
        JSONObject result = new JSONObject();
        result.put("result", "ok");
        result.put("records", records);
        result.put("total ", total );
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

Service:

List<MyRecord> getMyRecord((String uid, int page, int rows);
Long  getMyRecordCount(String uid);

ServiceImpl:

@Autowired
private ActivityMapper activityMapper;
   
   /**
   * 獲取分頁列表
   */
public List<MyRecord> getMyRecord(String uid, int page, int rows) {
    int i = (page - 1) * rows;
    List<MyRecord> records = activityMapper.getMyRecordToPage(uid, i, rows);
    return records;
}

/**
   * 獲取列表總數量
   */
public Long getMyRecorCount(String uid) {
     Long total= activityMapper.getMyRecordToPageCount(uid);
     return total;
}

Dao:

@Select("select * from myRecord where uid = #{0} order by create_time desc limit #{1},#{2}")
List<NineMyRecord> getMyWinRecordToPage(String uid, int i, int rows);

@Select("select count(*) from myRecord where uid = #{0}”)
Long  getMyWinRecordToPageCount(String uid);