【Spring】SpringMVC Mybatis 結合 PageHelper 實現分頁功能

一、引入pom依賴

<properties>
    <mybatis.version>3.2.8</mybatis.version>
    <mybatis.paginator.version>1.2.15</mybatis.paginator.version>
    <pagehelper.version>5.0.0</pagehelper.version>
</properties>

<dependencies>
    <dependency>
        <groupId>com.github.miemiedev</groupId>
        <artifactId>mybatis-paginator</artifactId>
        <version>${mybatis.paginator.version}</version>
    </dependency>
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>${pagehelper.version}</version>
    </dependency>
</dependencies>

 

二、在springmvc配置文件中加入插件

sqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--配置開啓自動匹配駝峯-->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <!--配置PageHelper分頁插件攔截器-->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!--            <property name="offsetAsPageNum" value="true"/>-->
            <!--            <property name="helperDialect" value="mysql"/>-->
            <property name="helperDialect" value="mysql"/>
            <!--            <property name="rowBoundsWithCount" value="true"/>-->
            <property name="reasonable" value="false"/>
        </plugin>
    </plugins>
</configuration>

 

三、在代碼中使用

@Override
public EUDataGridResult getContentList(Long id, int page, int rows) {
    TbContentExample example = new TbContentExample();
    TbContentExample.Criteria criteria = example.createCriteria();
    criteria.andCategoryIdEqualTo(id);

    // 分頁處理
    PageHelper.startPage(page, rows);
    // 查詢分類列表
    List<TbContent> lists = tbContentMapper.selectByExample(example);
    
    // 創建返回值對象
    EUDataGridResult result = new EUDataGridResult();
    result.setRows(lists);

    // 取記錄總數
    PageInfo pageInfo = new PageInfo(lists);
    result.setTotal(pageInfo.getTotal());
    result.setPages(pageInfo.getPages());

    return result;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章