Mybatis分页插件使用

导入分页工具类:

pom.xml:

<dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.10</version>
        </dependency>
    </dependencies>
声明 使用mybatis的分页插件:

sqlMapConfig.xml:

注意:plugins的位置别乱放

<configuration>
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>

测试:

RoleMapper接口:

 List<Role> getAllInfo();

RoleMapper.xml映射文件:

    <select id="getAllInfo" resultType="com.fsn.bean.Role">
        select r.id,r.name,r.battle,r.address from role r
    </select>

MybatisPage测试类:

import com.fsn.bean.Role;
import com.fsn.mapper.RoleMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MybatisPageTest {
    @Test
    public void test(){
        String filename="sqlMapConfig.xml";
        try {
            InputStream is=Resources.getResourceAsStream(filename);
            SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(is);
            SqlSession sqlSession=sqlSessionFactory.openSession();
            RoleMapper roleMapper=sqlSession.getMapper(RoleMapper.class);

            //当前的分页参数的设定必须要书写到我们使用mapper获取数据之前
            PageHelper.startPage(1,2 );
            List<Role> allInfo=roleMapper.getAllInfo();

            for (Role role : allInfo) {
                System.out.println(role);
            }
            //Mybatis将所有的分页数据存放到了我们工具PageInfo对象中
            PageInfo<Role> rolePageInfo=new PageInfo<>(allInfo);
            rolePageInfo.getPages();        //一共多少页
            rolePageInfo.getPageNum();      //当前是第几页
            rolePageInfo.getPageSize();     //一页几条数据
            rolePageInfo.getEndRow();       //当前页的最后一行的行号
            rolePageInfo.getList().size();      //集合中有几个结果
            rolePageInfo.getTotal();        //数据库中有多少条数据

            System.out.println(rolePageInfo.getPages());
            System.out.println(rolePageInfo.getPageNum());
            System.out.println(rolePageInfo.getPageSize());
            System.out.println(rolePageInfo.getEndRow());
            System.out.println(rolePageInfo.getList().size());
            System.out.println(rolePageInfo.getTotal());

            sqlSession.commit();
            sqlSession.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

结果:

posted @ 2020-06-30 22:08  zero6  阅读(200)  评论(0)    收藏  举报