1. 程式人生 > >MyBatis分頁填充page物件

MyBatis分頁填充page物件

這裡以一個專案中查詢文章的操作來做說明:

1、涉及的相關JavaBean

Article.java

public class Article extends BaseDomain {
    /**
     *置頂狀態
     */
    public static final String ARTICLE_TOP = "1";
    /**
     * 非置頂狀態
     */
    public static final String ARTICLE_UNTOP = "0";
    private String id;

	private String title;

    private String description;

    private String pic;

    private String content;

    private Long click;

    private Timestamp createTime;

    private Timestamp updateTime;

    private String categoryId;

    private String username;

    private Long commentNum;

    private String isTop = ARTICLE_UNTOP;

    private Category category;

    private List<Keyword> keywords;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getPic() {
        return pic;
    }

    public void setPic(String pic) {
        this.pic = pic;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Long getClick() {
        return click;
    }

    public void setClick(Long click) {
        this.click = click;
    }

    public Timestamp getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Timestamp createTime) {
        this.createTime = createTime;
    }

    public Timestamp getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Timestamp updateTime) {
        this.updateTime = updateTime;
    }

    public String getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(String categoryId) {
        this.categoryId = categoryId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Long getCommentNum() {
        return commentNum;
    }

    public void setCommentNum(Long commentNum) {
        this.commentNum = commentNum;
    }

    public String getIsTop() {
        return isTop;
    }

    public void setIsTop(String isTop) {
        this.isTop = isTop;
    }

    public List<Keyword> getKeywords() {
        return keywords;
    }

    public void setKeywords(List<Keyword> keywords) {
        this.keywords = keywords;
    }

    public Category getCategory() {
        return category;
    }

    public void setCategory(Category category) {
        this.category = category;
    }
}

Page.java:

public class Page<T> extends BaseDomain implements Serializable {

	private static int DEFAULT_PAGE_SIZE = 20;

    private long startIndex = 1; //當前記錄開始數

	private int pageSize = DEFAULT_PAGE_SIZE; // 每頁的記錄數

    private long totalCount; // 總記錄數

    private long totalPage; // 總頁數

	private List<T> data; // 當前頁中存放的記錄,型別一般為List

	/**
	 * 構造方法,只構造空頁.
	 */
	public Page() {
		this(0, DEFAULT_PAGE_SIZE, 0, 0, new ArrayList());
	}

    /**
     * 構造方法
     *
     * @param startIndex 當前記錄起始數
     * @param pageSize  本頁容量
     * @param totalCount 資料庫中總記錄條數
     * @param totalPage 資料庫中總頁數
     * @param data   本頁包含的資料
     */
	public Page(long startIndex, int pageSize, long totalCount, long totalPage, List<T> data) {
		this.startIndex = startIndex;
        this.pageSize = pageSize;
        this.totalCount = totalCount;
        this.totalPage = totalPage;
		this.data = data;
	}

    /**
     * 取該頁當前頁碼,頁碼從1開始.
     */
    public long getCurrentPage() {
        return startIndex / pageSize + 1;
    }

	/**
	 * 該頁是否有下一頁.
	 */
	public boolean isHasNextPage() {
		return this.getCurrentPage() < this.getTotalPage();
	}

	/**
	 * 該頁是否有上一頁.
	 */
	public boolean isHasPreviousPage() {
		return this.getCurrentPage() > 1;
	}

    public long getStartIndex() {
        return startIndex;
    }

    public void setStartIndex(long startIndex) {
        this.startIndex = startIndex;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public long getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(long totalCount) {
        this.totalCount = totalCount;
    }

    public long getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(long totalPage) {
        this.totalPage = totalPage;
    }

    public List<T> getData() {
        return data;
    }

    public void setData(List<T> data) {
        this.data = data;
    }
}

2、介面

ArticleDao.java

@Repository
public interface ArticleDao {
       /**
     * 分頁查詢函式
     *
     * @param parameters
     * 引數通過map傳遞,需要引數 startIndex pageSize 以及 需要查詢的引數
     */
    public Page<T> pagedQuery(Map<String, Object> parameters);
}

3、配置檔案

ArticleDaoMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="top.eussi.dao.ArticleDao" >
    <!-- 分頁查詢 -->
    <resultMap id="LightResultMap" type="Article" >
        <id column="id" property="id" jdbcType="VARCHAR" />
        <result column="title" property="title" jdbcType="VARCHAR" />
        <result column="description" property="description" jdbcType="VARCHAR" />
        <result column="pic" property="pic" jdbcType="VARCHAR" />
        <result column="content" property="content" jdbcType="VARCHAR" />
        <result column="click" property="click" jdbcType="INTEGER" />
        <result column="create_time" property="createTime" jdbcType="TIMESTAMP" />
        <result column="update_time" property="updateTime" jdbcType="TIMESTAMP" />
        <result column="category_id" property="categoryId" jdbcType="VARCHAR" />
        <result column="username" property="username" jdbcType="VARCHAR" />
        <result column="comment_num" property="commentNum" jdbcType="INTEGER" />
        <result column="is_top" property="isTop" jdbcType="VARCHAR" />
    </resultMap>

    <resultMap type="Page" id="PageResultMap">
        <id column="startIndex" property="startIndex"/>
        <id column="pageSize" property="pageSize"/>
        <id column="totalCount" property="totalCount"/>
        <id column="totalPage" property="totalPage"/>
        <collection column="{startIndex=startIndex,pageSize=pageSize}" property="data" ofType="Article" select="getPageArticle"/>
    </resultMap>

    <sql id="Page_Column_Article" >
        id,
        title,
        description,
        pic,
        click,
        create_time,
        update_time,
        category_id,
        username,
        comment_num,
        is_top
    </sql>

    <select id="getPageArticle" resultMap="LightResultMap" parameterType="hashmap" >
        select
        <include refid="Page_Column_Article" />
        from t_article
        ORDER BY create_time DESC
        limit #{startIndex}, #{pageSize}
    </select>

    <!-- #是採用佔用符, $是直接取到值 -->
    <select id="pagedQuery" parameterType="hashmap" resultMap="PageResultMap">
        select
        count(1) totalCount,
        ceil(count(1)/${pageSize}) totalPage,
        ${startIndex} startIndex,
        ${pageSize} pageSize
        from t_article
    </select>
</mapper>

4、測試類:

articleDaoTest.java:

@ContextConfiguration("classpath*:/spring_conf/blog-dao.xml")
public class articleDaoTest extends AbstractTransactionalTestNGSpringContextTests{

    @Autowired
    private ArticleDao articleDao;

    public void setArticleDao(ArticleDao articleDao) {
        this.articleDao = articleDao;
    }

    @Test
    public void getPageArticle() {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("startIndex", 1);
        hashMap.put("pageSize", 1);
        Page page = articleDao.pagedQuery(hashMap);
        System.out.println(page.toString());
    }
}

網上類似分頁外掛,攔截器實現的分頁方式暫時未嘗試,採用這種傳統的分頁方法,使用中最大的失誤就是page中屬性要和mapper檔案中使用的屬性對應上,花了較多時間,記錄一下!!!