1,配置PageHelper分页插件:
Config PageHelper
//在mybatis配置文件添加配置
1. Using in mybatis-config.xml
<!--
In the configuration file,
plugins location must meet the requirements as the following order:
properties?, settings?,
typeAliases?, typeHandlers?,
objectFactory?,objectWrapperFactory?,
plugins?,
environments?, databaseIdProvider?, mappers?
-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!-- config params as the following -->
<property name="param1" value="value1"/>
</plugin>
</plugins>
//在spring配置文件添加配置
2. Using in Spring application.xml
config org.mybatis.spring.SqlSessionFactoryBean as following:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- other configuration -->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<!-- config params as the following -->
<value>
param1=value1
</value>
</property>
</bean>
</array>
</property>
</bean>
这里选第一种方法,可直接复制文件 文件名:Mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!-- 打印查询语句 -->
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
<plugins>
<!-- com.github.pagehelper为PageHelper类所在包名 -->
<plugin interceptor="com.github.pagehelper.PageHelper">
<!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库 -->
<property name="dialect" value="mysql" />
</plugin>
</plugins>
</configuration>
使用插件:
编写mapper.xml文件
<select id="selectByPageAndSelections" resultMap="BaseResultMap">
SELECT *
FROM doc
ORDER BY doc_abstract
</select>
然后在Mapper.java中编写对应的接口
public List<Doc> selectByPageAndSelections();
测试
@Service
public class DocServiceImpl implements IDocService {
@Autowired
private DocMapper docMapper;
@Override
public PageInfo<Doc> selectDocByPage1(int currentPage, int pageSize) {
//先设置插件, currentPage为第几页, pageSize 每页大小
PageHelper.startPage(currentPage, pageSize);
List<Doc> docs = docMapper.selectByPageAndSelections();
//组装PageInfo, 里面包含了很多数据,包括总页数一系列数据,可查看类获取
PageInfo<Doc> pageInfo = new PageInfo<>(docs);
return pageInfo;
}
}