https://blog.csdn.net/xinyuezitang/article/details/84324359
用limit 实现java的简单分页
xinyuezitang 2018-11-21 16:01:13 4447 收藏 9
分类专栏: Java 小Demo 文章标签: 分页 limit mysql 实现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:
@Autowiredprivate 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);