数据展示,离不开分页,我们可以生写,更可以使用插件。pagehelper可以方便的帮我们做到这一点。
怎么用呢?
1、如果是maven 项目,首先得添加maven依赖。我使用的是2018年最新版本。
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.4</version> </dependency>
2、核心文件的配置有两种方式,我这里使用 spring核心文件的配置方式
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <property name="plugins"> <array> <bean class="com.github.pagehelper.PageInterceptor"> <property name="properties"> <!-- config params as the following --> <value> helperDialect:mysql reasonable:false </value> </property> </bean> </array> </property> </bean>
3、新建接口和实现类
public interface TuserServices { PageInfo<Tuser> queryPaging(int pageNum, int pageSize); }
实现类核心代码如下:
@Override public PageInfo<Tuser> queryPaging(int pageNum, int pageSize) { PageHelper.startPage(pageNum, pageSize); List<Tuser> tuserList=tuserMapper.queryPaging(); PageInfo<Tuser> pageInfo=new PageInfo<Tuser>(tuserList); return pageInfo; }
完成了这一步,就可以进入测试了。
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:ApplicationContext.xml"}) public class TuserServicesTest { @Resource private TuserServices tuserServices; @Test public void queryPaging() throws Exception { PageInfo<Tuser> pageInfo=tuserServices.queryPaging(0,2); List<Tuser> list=pageInfo.getList(); for (Tuser tuser : list) { System.out.println(tuser); } } }
结果如下:
运行正常。当然也有其它的运行方法,具体方法请去官网查找。