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文件中使用的属性对应上,花了较多时间,记录一下!!!

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis-Plus 是一个优秀的 MyBatis 增强工具包,提供了很多便捷的功能,其中包括自动分页功能。 在 MyBatis-Plus 中,实现自动分页可以通过使用 `Page` 类来实现。首先,你需要创建一个 `Page` 对象,并设置分页的参数,例如当前页码和每页显示的记录数。接下来,你可以调用 `Page` 对象的 `setCurrent()` 方法设置当前页码,调用 `setSize()` 方法设置每页显示的记录数。 一旦你设置好了分页参数,你可以在查询方法中使用 `Page` 对象作为参数,并在查询语句中使用 MyBatis-Plus 提供的分页插件进行分页查询。查询结果会自动填充到 `Page` 对象中的 `records` 属性中,并且分页信息也会被填充到 `Page` 对象的其他属性中,例如总记录数、总页数等。 以下是一个示例代码: ```java // 创建分页对象 Page<User> page = new Page<>(1, 10); // 当前页码为 1,每页显示 10 条记录 // 执行分页查询 IPage<User> userPage = userMapper.selectPage(page, null); // 查询结果 List<User> userList = userPage.getRecords(); ``` 在上述示例中,`userMapper` 是 MyBatis 的映射接口,`selectPage()` 方法会执行分页查询,并将结果填充到 `userList` 中。 需要注意的是,为了使用 MyBatis-Plus 的自动分页功能,你需要在项目中引入 MyBatis-Plus 的依赖,并正确配置 MyBatis-Plus 相关的配置文件。 希望对你有所帮助!如有更多问题,请继续提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值