mybatis中PageHelper的使用
一、引入pagehelper的jar包 如果是maven项目,pom里添加依赖:com.github.pagehelperpagehelper4.1.4二、在mybatis的配置文件中配置拦截(也可以在spring配置文件中配置) 小编在mybatis配置文件SqlMapConf
文章共1,060字 · 阅读需要大约4分钟
一键AI生成摘要,助你高效阅读
问答
·
一、引入pagehelper的jar包
如果是maven项目,pom里添加依赖:
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.4</version>
</dependency>
二、在mybatis的配置文件中配置拦截(也可以在spring配置文件中配置)
小编在mybatis配置文件SqlMapConfig.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>
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<!--设置数据可类型Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->
<property name="dialect" value="mysql"/>
</plugin>
</plugins>
</configuration>
在spring中配置如下:
<!--配置SqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml" />
<property name="typeAliasesPackage" value="com.aoChine.model.entity" />
<property name="mapperLocations" value="classpath:mapper/*.xml" />
<!-- 配置mybatis分页插件PageHelper -->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<!-- 什么都不配,使用默认的配置 -->
<value></value>
</property>
</bean>
</array>
</property>
</bean>
三、代码中如何实现
Service中一个方法示例:
EasyUIDataGridResult是自己封装的一个pojo,如下:
public class EasyUIDataGridResult implements Serializable {
private long total;
private List rows;
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public List getRows() {
return rows;
}
public void setRows(List rows) {
this.rows = rows;
}
}
如果不需要的话直接返回PageInfo就可以,例如:
四、注意事项
分页不安全的情况
PageHelper 方法使用了静态的 ThreadLocal 参数,分页参数和线程是绑定的。
只要你可以保证在 PageHelper 方法调用后紧跟 MyBatis 查询方法,这就是安全的。因为 PageHelper 在 finally 代码段中自动清除了 ThreadLocal 存储的对象。
如下代码是不安全的:
PageHelper.startPage(1, 10);
List<Country> list;
if(param1 != null){
list = countryMapper.selectIf(param1);
} else {
list = new ArrayList<Country>();
}
这种情况下由于 param1 存在 null 的情况,就会导致 PageHelper 生产了一个分页参数,但是没有被消费,这个参数就会一直保留在这个线程上。当这个线程再次被使用时,就可能导致不该分页的方法去消费这个分页参数,这就产生了莫名其妙的分页。
写成如下便安全了:
List<Country> list;
if(param1 != null){
PageHelper.startPage(1, 10);
list = countryMapper.selectIf(param1);
} else {
list = new ArrayList<Country>();
}
另外也可以手动清理ThreadLocal存储的分页参数:
PageHelper.clearPage();
更多推荐
已为社区贡献1条内容
所有评论(0)