mybatis分页实现(非插件方式)
2016-12-18 12:03
459 查看
前面一篇文章介绍了通过拦截器发方式实现mybatis分页(应该是比较常用的一种方式,网上搜索结果较多),这里介绍另一种方式:通过代码封装,不改变mybatis框架的任何东西(个人推荐使用该方式),这个代码是我老大写的,个人觉得很好,原理也很简单,修改也很容易,所以贴出来,供大家参考。
package com.dnkx.base.service;
import com.dnkx.base.persistance.BaseMapper;
import com.dnkx.base.utils.PaginationSupport;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* Created by baowp on 2015/8/18.
*/
public interface BaseService<T extends BaseMapper<E>,E extends Serializable> {
E get(Long id);
int save(E e);
int update(E e);
int delete(Long id);
/**
* 按条件查询列表
* @param params
* @return
*/
List<E> list(Map params);
/**
* 按条件查询记录数
* @param params
* @return
*/
int count(Map params);
/**
* 按条件分布查询列表
* @param params
* @return
*/
PaginationSupport<E> pageList(Map params);
/**
* 按条件分布查询列表
* @param params
* @return
*/
PaginationSupport<E> pageList(E params);
}
上面这个是基础的service类,需要分页的业务service都继承于这个基础的service
下面的实现类和Mapper类同理:
service实现类,里面包含了分页的实现,原理很简单的
package com.dnkx.base.service.impl;
import com.dnkx.base.persistance.BaseMapper;
import com.dnkx.base.service.BaseService;
import com.dnkx.base.utils.PaginationSupport;
import com.dnkx.common.utils.BeanUtil;
import org.slf4j.Logger;
import org.sl
4000
f4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* Created by baowp on 2015/8/18.
*/
public class BaseServiceImpl<T extends BaseMapper<E>, E extends Serializable> implements BaseService<T, E> {
protected final Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
protected T mapper;
@Override
public E get(Long id) {
return mapper.get(id);
}
@Override
public int save(E e) {
return mapper.save(e);
}
@Override
public int update(E e) {
return mapper.update(e);
}
@Override
public int delete(Long id) {
return mapper.delete(id);
}
@Override
public List<E> list(Map params) {
return mapper.list(params);
}
@Override
public int count(Map params) {
return mapper.count(params);
}
@Override
public PaginationSupport<E> pageList(Map params) {
if (params.get("pageSize") == null || params.get("pageNo") == null) {
throw new RuntimeException("You must specify pageSize and pageNo in the params when executing pageList method");
}
int pageSize = (Integer) params.get("pageSize");
int pageNo = (Integer) params.get("pageNo");
if (pageNo < 1) pageNo = 1;
//for oracle
int startRow = (pageNo - 1) * pageSize;
int endRow = startRow + pageSize;
params.put("startRow", startRow);
params.put("endRow", endRow);
//for mysql
params.put("startIndex", startRow);
List<E> list = mapper.pageList(params);
int total = count(params);
if (logger.isInfoEnabled()) {
logger.info("Get totalCount is {} when executing pageList,pageSize is {},pageNo is {}", total, pageSize, pageNo);
}
return new PaginationSupport<>(list, total, pageSize, startRow);
}
@Override
public PaginationSupport<E> pageList(E params) {
return pageList(BeanUtil.bean2map(params));
}
}
Mapper基础类(更习惯叫DAO):
package com.dnkx.base.persistance;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* Created by baowp on 2015/8/18.
*/
public interface BaseMapper<E extends Serializable> {
E get(Long id);
int save(E e);
int update(E e);
int delete(Long id);
/**
* 按条件查询列表
* @param params
* @return
*/
List<E> list(Map params);
/**
* 按条件查询记录数
* @param params
* @return
*/
int count(Map params);
/**
* 按条件分布查询列表
* @param params
* @return
*/
List<E> pageList(Map params);
}
最后是一个分页实体对象
package com.dnkx.base.utils;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
public class PaginationSupport<E> implements Iterable<E>, Serializable {
public final static int PAGESIZE = 2;
private int pageSize = PAGESIZE;
private int totalCount;
private int currentPage;
private int nextPage;
private int previousPage;
private int startIndex;
private int[] indexes = new int[0];
private int nextIndex;
private int previousIndex;
private int pageCount;
private List<E> items;
private int lastIndex;
public PaginationSupport(){}
public PaginationSupport(int pageSize, int startIndex) {
setPageSize(pageSize);
startIndex(startIndex);
}
public PaginationSupport(List<E> items, int totalCount) {
setPageSize(PAGESIZE);
totalCount(totalCount);
setItems(items);
startIndex(0);
}
public PaginationSupport(List<E> items, int totalCount, int startIndex) {
setPageSize(PAGESIZE);
totalCount(totalCount);
setItems(items);
startIndex(startIndex);
}
public PaginationSupport(List<E> items, int totalCount, int pageSize,
int startIndex) {
setPageSize(pageSize);
totalCount(totalCount);
setItems(items);
startIndex(startIndex);
}
public void totalCount(int totalCount) {
if (totalCount > 0) {
this.totalCount = totalCount;
int count = totalCount / pageSize;
if (totalCount % pageSize > 0)
count++;
indexes = new int[count];
for (int i = 0; i < count; i++) {
indexes[i] = pageSize * i;
}
} else {
this.totalCount = 0;
}
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getTotalCount() {
return totalCount;
}
public void setIndexes(int[] indexes) {
this.indexes = indexes;
}
public int[] getIndexes() {
return indexes;
}
public void startIndex(int startIndex) {
if (totalCount <= 0)
this.startIndex = 0;
else if (startIndex >= totalCount)
this.startIndex = indexes[indexes.length - 1];
else if (startIndex < 0)
this.startIndex = 0;
else {
this.startIndex = indexes[startIndex / pageSize];
}
{
pageCount = indexes.length;
currentPage = startIndex / pageSize + 1;
previousPage = currentPage > 1 ? currentPage - 1 : currentPage;
nextPage = currentPage < pageCount ? currentPage + 1 : currentPage;
nextIndex = startIndex + pageSize;
nextIndex = nextIndex >= totalCount ? startIndex : nextIndex;
previousIndex = startIndex - pageSize;
previousIndex = previousIndex < 0 ? 0 : previousIndex;
lastIndex = indexes.length == 0 ? 0 : indexes[indexes.length - 1];
}
}
public void setStartIndex(int startIndex) {
this.startIndex = startIndex;
}
public int getStartIndex() {
return startIndex;
}
public void setNextIndex(int nextIndex) {
this.nextIndex = nextIndex;
}
public int getNextIndex() {
return nextIndex;
}
public void setPreviousIndex(int previousIndex) {
this.previousIndex = previousIndex;
}
public int getPreviousIndex() {
return previousIndex;
}
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
public int getPageCount() {
return pageCount;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public void setLastIndex(int lastIndex) {
this.lastIndex = lastIndex;
}
public int getLastIndex() {
return lastIndex;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public List<E> getItems() {
return items;
}
public void setItems(List<E> items) {
this.items = items;
}
public int getNextPage() {
return nextPage;
}
public void setNextPage(int nextPage) {
this.nextPage = nextPage;
}
public int getPreviousPage() {
return previousPage;
}
public void setPreviousPage(int previousPage) {
this.previousPage = previousPage;
}
public Iterator<E> iterator() {
return items.iterator();
}
public int size() {
return items.size();
}
}
下面给一个使用实例:
service类
public interface CategoryService extends BaseService<CategoryMapper,CategoryEntity>{
}
setviceImpl类
@Service("categoryService")
public class CategoryServiceImpl extends BaseServiceImpl<CategoryMapper,CategoryEntity> implements CategoryService{
}
Mapper类
public interface CategoryMapper extends BaseMapper<CategoryEntity>{}
Controller类
@Controller
public class CategoryController {
@Resource
private CategoryService categoryService;
@Resource
private HttpServletRequest request;
private final Logger logger= LoggerFactory.getLogger(getClass());
@ResponseBody
@RequestMapping("/category/list")
public String list(){
Map map=new HashMap();
map.put("pageSize",20);
map.put("pageNo",1);
PaginationSupport<CategoryEntity> entity=categoryService.pageList(map);
logger.info("====>{},{}",entity.getItems().size(),entity.getPageCount());
return "";
}
}
mapper.xml
<select id="count" parameterType="java.util.Map" resultType="int">
select count(id) from com_category
<include refid="queryConditions"/>
</select>
<select id="pageList" resultMap="BaseResultMap" parameterType="java.util.Map" >
select
<include refid="Base_Column_List" />
from com_category
<include refid="queryConditions" />
limit #{startIndex},#{pageSize}
</select>
表达能力欠佳,所以代码算是给的比较全了,里面的原理都很简单,了解OOP的应该都能看明白!!!
package com.dnkx.base.service;
import com.dnkx.base.persistance.BaseMapper;
import com.dnkx.base.utils.PaginationSupport;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* Created by baowp on 2015/8/18.
*/
public interface BaseService<T extends BaseMapper<E>,E extends Serializable> {
E get(Long id);
int save(E e);
int update(E e);
int delete(Long id);
/**
* 按条件查询列表
* @param params
* @return
*/
List<E> list(Map params);
/**
* 按条件查询记录数
* @param params
* @return
*/
int count(Map params);
/**
* 按条件分布查询列表
* @param params
* @return
*/
PaginationSupport<E> pageList(Map params);
/**
* 按条件分布查询列表
* @param params
* @return
*/
PaginationSupport<E> pageList(E params);
}
上面这个是基础的service类,需要分页的业务service都继承于这个基础的service
下面的实现类和Mapper类同理:
service实现类,里面包含了分页的实现,原理很简单的
package com.dnkx.base.service.impl;
import com.dnkx.base.persistance.BaseMapper;
import com.dnkx.base.service.BaseService;
import com.dnkx.base.utils.PaginationSupport;
import com.dnkx.common.utils.BeanUtil;
import org.slf4j.Logger;
import org.sl
4000
f4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* Created by baowp on 2015/8/18.
*/
public class BaseServiceImpl<T extends BaseMapper<E>, E extends Serializable> implements BaseService<T, E> {
protected final Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
protected T mapper;
@Override
public E get(Long id) {
return mapper.get(id);
}
@Override
public int save(E e) {
return mapper.save(e);
}
@Override
public int update(E e) {
return mapper.update(e);
}
@Override
public int delete(Long id) {
return mapper.delete(id);
}
@Override
public List<E> list(Map params) {
return mapper.list(params);
}
@Override
public int count(Map params) {
return mapper.count(params);
}
@Override
public PaginationSupport<E> pageList(Map params) {
if (params.get("pageSize") == null || params.get("pageNo") == null) {
throw new RuntimeException("You must specify pageSize and pageNo in the params when executing pageList method");
}
int pageSize = (Integer) params.get("pageSize");
int pageNo = (Integer) params.get("pageNo");
if (pageNo < 1) pageNo = 1;
//for oracle
int startRow = (pageNo - 1) * pageSize;
int endRow = startRow + pageSize;
params.put("startRow", startRow);
params.put("endRow", endRow);
//for mysql
params.put("startIndex", startRow);
List<E> list = mapper.pageList(params);
int total = count(params);
if (logger.isInfoEnabled()) {
logger.info("Get totalCount is {} when executing pageList,pageSize is {},pageNo is {}", total, pageSize, pageNo);
}
return new PaginationSupport<>(list, total, pageSize, startRow);
}
@Override
public PaginationSupport<E> pageList(E params) {
return pageList(BeanUtil.bean2map(params));
}
}
Mapper基础类(更习惯叫DAO):
package com.dnkx.base.persistance;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* Created by baowp on 2015/8/18.
*/
public interface BaseMapper<E extends Serializable> {
E get(Long id);
int save(E e);
int update(E e);
int delete(Long id);
/**
* 按条件查询列表
* @param params
* @return
*/
List<E> list(Map params);
/**
* 按条件查询记录数
* @param params
* @return
*/
int count(Map params);
/**
* 按条件分布查询列表
* @param params
* @return
*/
List<E> pageList(Map params);
}
最后是一个分页实体对象
package com.dnkx.base.utils;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
public class PaginationSupport<E> implements Iterable<E>, Serializable {
public final static int PAGESIZE = 2;
private int pageSize = PAGESIZE;
private int totalCount;
private int currentPage;
private int nextPage;
private int previousPage;
private int startIndex;
private int[] indexes = new int[0];
private int nextIndex;
private int previousIndex;
private int pageCount;
private List<E> items;
private int lastIndex;
public PaginationSupport(){}
public PaginationSupport(int pageSize, int startIndex) {
setPageSize(pageSize);
startIndex(startIndex);
}
public PaginationSupport(List<E> items, int totalCount) {
setPageSize(PAGESIZE);
totalCount(totalCount);
setItems(items);
startIndex(0);
}
public PaginationSupport(List<E> items, int totalCount, int startIndex) {
setPageSize(PAGESIZE);
totalCount(totalCount);
setItems(items);
startIndex(startIndex);
}
public PaginationSupport(List<E> items, int totalCount, int pageSize,
int startIndex) {
setPageSize(pageSize);
totalCount(totalCount);
setItems(items);
startIndex(startIndex);
}
public void totalCount(int totalCount) {
if (totalCount > 0) {
this.totalCount = totalCount;
int count = totalCount / pageSize;
if (totalCount % pageSize > 0)
count++;
indexes = new int[count];
for (int i = 0; i < count; i++) {
indexes[i] = pageSize * i;
}
} else {
this.totalCount = 0;
}
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getTotalCount() {
return totalCount;
}
public void setIndexes(int[] indexes) {
this.indexes = indexes;
}
public int[] getIndexes() {
return indexes;
}
public void startIndex(int startIndex) {
if (totalCount <= 0)
this.startIndex = 0;
else if (startIndex >= totalCount)
this.startIndex = indexes[indexes.length - 1];
else if (startIndex < 0)
this.startIndex = 0;
else {
this.startIndex = indexes[startIndex / pageSize];
}
{
pageCount = indexes.length;
currentPage = startIndex / pageSize + 1;
previousPage = currentPage > 1 ? currentPage - 1 : currentPage;
nextPage = currentPage < pageCount ? currentPage + 1 : currentPage;
nextIndex = startIndex + pageSize;
nextIndex = nextIndex >= totalCount ? startIndex : nextIndex;
previousIndex = startIndex - pageSize;
previousIndex = previousIndex < 0 ? 0 : previousIndex;
lastIndex = indexes.length == 0 ? 0 : indexes[indexes.length - 1];
}
}
public void setStartIndex(int startIndex) {
this.startIndex = startIndex;
}
public int getStartIndex() {
return startIndex;
}
public void setNextIndex(int nextIndex) {
this.nextIndex = nextIndex;
}
public int getNextIndex() {
return nextIndex;
}
public void setPreviousIndex(int previousIndex) {
this.previousIndex = previousIndex;
}
public int getPreviousIndex() {
return previousIndex;
}
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
public int getPageCount() {
return pageCount;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public void setLastIndex(int lastIndex) {
this.lastIndex = lastIndex;
}
public int getLastIndex() {
return lastIndex;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public List<E> getItems() {
return items;
}
public void setItems(List<E> items) {
this.items = items;
}
public int getNextPage() {
return nextPage;
}
public void setNextPage(int nextPage) {
this.nextPage = nextPage;
}
public int getPreviousPage() {
return previousPage;
}
public void setPreviousPage(int previousPage) {
this.previousPage = previousPage;
}
public Iterator<E> iterator() {
return items.iterator();
}
public int size() {
return items.size();
}
}
下面给一个使用实例:
service类
public interface CategoryService extends BaseService<CategoryMapper,CategoryEntity>{
}
setviceImpl类
@Service("categoryService")
public class CategoryServiceImpl extends BaseServiceImpl<CategoryMapper,CategoryEntity> implements CategoryService{
}
Mapper类
public interface CategoryMapper extends BaseMapper<CategoryEntity>{}
Controller类
@Controller
public class CategoryController {
@Resource
private CategoryService categoryService;
@Resource
private HttpServletRequest request;
private final Logger logger= LoggerFactory.getLogger(getClass());
@ResponseBody
@RequestMapping("/category/list")
public String list(){
Map map=new HashMap();
map.put("pageSize",20);
map.put("pageNo",1);
PaginationSupport<CategoryEntity> entity=categoryService.pageList(map);
logger.info("====>{},{}",entity.getItems().size(),entity.getPageCount());
return "";
}
}
mapper.xml
<select id="count" parameterType="java.util.Map" resultType="int">
select count(id) from com_category
<include refid="queryConditions"/>
</select>
<select id="pageList" resultMap="BaseResultMap" parameterType="java.util.Map" >
select
<include refid="Base_Column_List" />
from com_category
<include refid="queryConditions" />
limit #{startIndex},#{pageSize}
</select>
表达能力欠佳,所以代码算是给的比较全了,里面的原理都很简单,了解OOP的应该都能看明白!!!
相关文章推荐
- mybatis id 保存UUID
- more、less 和 most 的区别
- AJAX实现瀑布流触发分页与分页触发瀑布流的方法
- 十万条Access数据表分页的两个解决方法
- PHP+jquery+ajax实现分页
- sqlserver关于分页存储过程的优化【让数据库按我们的意思执行查询计划】
- 高效的mysql分页方法及原理
- asp又一个分页的代码例子
- 通用SQL存储过程分页以及asp.net后台调用的方法
- SqlServer 2000、2005分页存储过程整理第1/3页
- JQuery的Pager分页器实现代码
- ADO存取数据库时如何分页显示
- MySQL学习笔记之数据定义表约束,分页方法总结
- Mysql Limit 分页查询优化详解
- 透彻掌握ASP分页技术很详细的分析
- jQuery实现的简单分页示例
- Android ListView分页功能实现方法
- 在ASP.NET 2.0中操作数据之二十四:分页和排序报表数据
- ajax无刷新分页的简单实现
- 一条SQL语句搞定Sql2000 分页