PageHelper分页插件在网上有很多配置都是xml配置的,搜了半天都没有找到合适的,有一篇文章是关于注解配置的,但是版本太旧,代码编译就会报错,决定自己整理一篇,以供参考。
在华超同学参考源码的情况下,做出了最新的注解版配置,主要配置如下
(1)pom.xml导入依赖
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
(2)在核心配置类中配置PageInterceptor
@Bean("sqlSessionFactory")
public SqlSessionFactoryBean newSqlSessionFactoryBean(@Autowired DataSource dataSource) throws IOException{
//设置mapper文件关联
SqlSessionFactoryBean fBean=new SqlSessionFactoryBean();
fBean.setDataSource(dataSource);
Resource[] mapperLocations=new PathMatchingResourcePatternResolver().getResources("classpath:mapper/sys/*.xml");
fBean.setMapperLocations(mapperLocations);
//log4j配置
org.apache.ibatis.session.Configuration configuration=new org.apache.ibatis.session.Configuration();
configuration.setLogImpl(Log4jImpl.class);
fBean.setConfiguration(configuration);
//pageHelper分页配置(只参考这部分配置就可以了)
PageInterceptor pageInterceptor = new PageInterceptor();
Properties properties=new Properties();
//下面这行代码可以不配置,因为在源码中会默认给properties进行如下配置
/* properties.put("dialect", "com.github.pagehelper.PageHelper");*/
pageInterceptor.setProperties(properties);
fBean.setPlugins(new Interceptor[]{pageInterceptor});
return fBean;
}
(3)更改dao,mapper,sercice,在serviceImpl中应用PageHelper
dao
List<SysConfig> findPageObjects(@Param("name") String name);
mapper(不需要sql语句不需要limit #{startIndex},#{pageSize})
<select id="findPageObjects" resultType="com.jt.sys.entity.SysConfig">
select * from sys_configs
<include refid="queryWhereId"/>
order by createdTime desc
</select>
service
PageObject<SysConfig> findPageObjects(
String name,
Integer pageCurrent);
serviceImpl(pageObject是我们创建的一个值对象,里面封装了当前页,页面大小,总行数,总页数,数据 )
@Override
public PageObject<SysConfig> findPageObjects(String name, Integer pageCurrent) {
int pageSize=3;
PageHelper.startPage(pageCurrent, pageSize);
List<SysConfig> list = sysConfigDao.findPageObjects(name);
PageInfo<SysConfig> pageInfo = new PageInfo<>(list,5);
PageObject<SysConfig> pageObject = new PageObject<>();
pageObject.setPageCurrent(pageCurrent);
pageObject.setRecords(list);
pageObject.setPageCount(pageInfo.getPages());
pageObject.setPageSize(pageSize);
pageObject.setRowCount((int) pageInfo.getTotal());
return pageObject;
}