1. 程式人生 > >mybatis分頁實現(非外掛方式)

mybatis分頁實現(非外掛方式)

前面一篇文章介紹了通過攔截器發方式實現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.slf4j.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的應該都能看明白!!!