Mybatis分页插件
Categories: MyBatis
PageHelper是一款好用的开源免费的Mybatis第三方物理分页插件。
1.导入jar包
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.2.1</version>
</dependency>
2.配置文件
在mybatis-config.xml中添加配置
<!--plugins在settings之后,environments之前-->
<plugins>
<!-- PageHelper4.1.1 -->
<plugin interceptor="com.github.pagehelper.PageHelper">
<property name="dialect" value="mysql"/><!--数据库方言-->
<!-- 3.3.0版本可用 - 分页参数合理化,默认false禁用 -->
<!-- 启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页 -->
<!-- 禁用合理化时,如果pageNum<1或pageNum>pages会返回空数据 -->
<property name="reasonable" value="false"/>
</plugin>
</plugins>
注:在mybatis和spring整合后没有mybatis-config.xml文件,该配置写在spring-config.xml的sqlSessionFactory切面下
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:dao/*.xml"/>
<property name="typeAliasesPackage" value="pojo"/>
<!--<property name="configLocation" value="classpath:mybatis-config.xml"/>-->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageHelper">
<property name="properties">
<value>
dialect=mysql
reasonable=true
</value>
</property>
</bean>
</array>
</property>
</bean>
3.测试代码
PageHelper.startPage(1, 5,"id desc");
List<Dept> deptList = session.selectList("DEPT.getAllDept");
PageInfo<Dept> page = new PageInfo<>(deptList);
System.out.println("总页数:" + page.getPages());
System.out.println("页码:" + page.getPageNum());
System.out.println("总条数:"+page.getTotal());
System.out.println(deptList.size());
for (Dept dept : deptList) {
System.out.println(dept.getName());
}