手工分页
手工分页用处:当数据使用mybatisPlus分页查询后,需要再次过滤掉筛选数据时,返回的总数失效,此时可以使用手工分页
kotlin手工分页工具类
@Component
class ManualPageUtils {
/**
* 封装手动分页
* @param list 数据集合
* @param start 起始页
* @param length 每页尺寸
*/
fun setPage(list: List<*>, start: Long, length: Long): Map<String, Any?> {
val result: MutableMap<String, Any?> = LinkedHashMap(8)
val totalCount = list.size
// 分页
var pageNum = totalCount / length
val surplus = totalCount % length
if (surplus > 0) {
pageNum += 1
}
result["total"] = totalCount
result["pages"] = pageNum
result["current"] = start
result["size"] = length
var pageResult: List<T> = arrayListOf()
if (totalCount != 0) {
pageResult = getPageSizeDataForRelations(list, length, start) as List<T>
}
result["records"] = pageResult
return result
}
/**
* 手动分页类
* @param datas
* @param pageSize
* @param pageNo
* @param <T>
* @return
</T> */
private fun <T> getPageSizeDataForRelations(datas: List<T>, pageSize: Long, pageNo: Long): List<T>? {
val startNum = (pageNo - 1) * pageSize + 1
if (startNum > datas.size) {
return null
}
val res: MutableList<T> = arrayListOf()
val rum = datas.size - startNum
if (rum < 0) {
return null
}
if (rum == 0L) {
val index = datas.size - 1
res.add(datas[index])
return res
}
return if (rum / pageSize >= 1) {
for (i in startNum until startNum + pageSize) {
res.add(datas[(i - 1).toInt()])
}
res
} else if (rum / pageSize == 0L && rum > 0) {
for (j in startNum..datas.size) {
res.add(datas[(j - 1).toInt()])
}
res
} else {
null
}
}
}