项目中配置的分页插件依赖为
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.7</version>
</dependency>
之前的项目代码编写分页的方式为,通过传入的条件,先查询总条数,这是第一次sql执行,然后,根据传入的页码、条数,拼凑limit条件,查询分页记录,这是第二次sql执行,如下
int start = (Integer.valueOf(pageNum)-1)*Integer.valueOf(pageSize);
int end = Integer.valueOf(pageSize);
String dataType = "dataType";
List<DataTypeList>list = dataTypeMapper.queryDataTypeList(request.getParameter(dataType),start,end);
for (DataTypeList dataTypeList : list) {
Date date = new Date(dataTypeList.getCheckTime());
dataTypeList.setCheckDate(sdf.format(date));
}
page.setList(list);
page.setPageSize(pageSize);
int total = dataTypeMapper.countByExample(request.getParameter(dataType));
page.setTotal(String.valueOf(total));
page.setPageNum(pageNum);
page.setPages(String.valueOf((total%Integer.valueOf(pageSize))>0?(total/Integer.valueOf(pageSize)+1):(total/Integer.valueOf(pageSize))));
可是这样的写法,有没有分页插件压根没影响啊,而且特别蠢,于是考虑改造,通过如下代码实现分页
PageHelper.startPage(Integer.valueOf(pageNum),Integer.valueOf(pageSize));
List<DataTypeList>list = dataTypeMapper.queryDataTypeList1(request.getParameter("templateId"));
PageInfo<DataTypeList> pageInfo = new PageInfo<DataTypeList>(list);
运行之后有了总条数等信息,但是分页却不生效,查询的是所有记录,于是,考虑增加配置,如下
pagehelper.helperDialect=mysq1
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSq1
如果自定义了数据库连接配置,那么需要用下面的方式,将分页插件定义到mybatis配置中,如下
@Bean
public SqlSessionFactory mnrSqlSessionFactory(DataSource mnrDataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(mnrDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(MnrDataSourceConfig.MAPPER_LOCATION));
org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
configuration.setMapUnderscoreToCamelCase(true);
sessionFactory.setConfiguration(configuration);
PageInterceptor pageHelper = new PageInterceptor();
Properties properties = new Properties();
properties.setProperty("reasonable","true");
pageHelper.setProperties(properties);
sessionFactory.setPlugins(new Interceptor[]{pageHelper});
return sessionFactory.getObject();
}
我这里加了驼峰自动转换,当然,也可以在xml文件配置,如下
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 其他配置 -->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<!-- 这里可以配置PageHelper的属性 -->
<props>
<prop key="reasonable">true</prop>
<prop key="supportMethodsArguments">true</prop>
<prop key="returnPageInfo">check</prop>
</props>
</property>
</bean>
</array>
</property>
</bean>
另外,如果更改依赖为pageHelper-spring-boot-starter的话
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.0</version>
</dependency>
直接编写分页代码即可,不需要额外配置
starter的autoConfiguratuin中自动配置了分页插件