对于使用Mybatis时,最头痛的就是写分页,需要先写一个查询count的select语句,然后再写一个真正分页查询的语句,当查询条件多了之后,会发现真不想花双倍的时间写count和select,可以发现,重复的代码太多,虽然说复制粘贴简单的很,但是文件的长度在成倍的增加,以后翻阅代码的时候头都能大了。
于是希望只写一个select语句,count由插件根据select语句自动完成。找啊找啊,发现PageHelperhttps://github.com/pagehelper/Mybatis-PageHelper 符合要求,于是就简单的写了一个测试项目
1,配置分页插件:
直接从官网上copy的如下: 两种配置方法
Config PageHelper
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>
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>
2,编写mapper.xml文件:
测试工程就不复杂了,简单的查询一个表,没有条件
<select id="selectByList" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user_t
</select>
然后在Mapper.java中编写对应的接口
public List<User> selectByList() {
return this.userDao.selectByList();
}
3,分页
@RequestMapping("/userList")
public String userList(@RequestParam(required=true,defaultValue="1") Integer page,HttpServletRequest request,Model model){
//PageHelper.startPage(page, pageSize);这段代码表示,程序开始分页了,page默认值是1,pageSize默认是10,意思是从第1页开始,每页显示10条记录。
PageHelper.startPage(page, 3);
List<User> userList = userService.selectByList();
PageInfo<User> p=new PageInfo<User>(userList);
model.addAttribute("page", p);
model.addAttribute("userList",userList);
return "showUser";
}
PageInfo这个类是插件里的类,非常方便的调用,分页再次提高性能:
//当前页
private int pageNum;
//每页的数量
private int pageSize;
//当前页的数量
private int size;
//排序
private String orderBy;
//由于startRow和endRow不常用,这里说个具体的用法
//可以在页面中"显示startRow到endRow 共size条数据"
//当前页面第一个元素在数据库中的行号
private int startRow;
//当前页面最后一个元素在数据库中的行号
private int endRow;
//总记录数
private long total;
//总页数
private int pages;
//结果集
private List<T> list;
//第一页
private int firstPage;
//前一页
private int prePage;
//下一页
private int nextPage;
//最后一页
private int lastPage;
//是否为第一页
private boolean isFirstPage = false;
//是否为最后一页
private boolean isLastPage = false;
//是否有前一页
private boolean hasPreviousPage = false;
//是否有下一页
private boolean hasNextPage = false;
//导航页码数
private int navigatePages;
//所有导航页号
private int[] navigatepageNums;
使用PageInfo这个类,你需要将查询出来的list放进去:
List<User> userList = userService.selectByList();
PageInfo<User> p=new PageInfo<User>(userList);
model.addAttribute("page", p);
前台页面
<body>
<center>
<table width="200" border="1">
<tr>
<th scope="col">序号</th>
<th scope="col">ID</th>
<th scope="col">姓名</th>
<th scope="col">密码</th>
<th scope="col">年龄</th>
</tr>
<c:forEach begin="0" step="1" items="${userList}" var="list" varStatus="userlist">
<tr>
<td>${userlist.count}</td>
<td>${list.id}</td>
<td>${list.userName}</td>
<td>${list.password}</td>
<td>${list.age}</td>
</tr>
</c:forEach>
</table>
<p>一共${page.pages}页</p>
<a href="userList?page=${page.firstPage}">第一页</a>
<a href="userList?page=${page.nextPage}">下一页</a>
<a href="userList?page=${page.prePage}">上一页</a>
<a href="userList?page=${page.lastPage}">最后页</a>
</center>
</body>
4. 什么时候会导致不安全的分页?
PageHelper 方法使用了静态的 ThreadLocal 参数,分页参数和线程是绑定的。
只要你可以保证在 PageHelper 方法调用后紧跟 MyBatis 查询方法,这就是安全的。因为 PageHelper 在 finally 代码段中自动清除了 ThreadLocal 存储的对象。
如果代码在进入 Executor 前发生异常,就会导致线程不可用,这属于人为的 Bug(例如接口方法和 XML 中的不匹配,导致找不到 MappedStatement 时), 这种情况由于线程不可用,也不会导致 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 存储的分页参数,可以像下面这样使用:
List<Country> list;
if(param1 != null){
PageHelper.startPage(1, 10);
try{
list = countryMapper.selectAll();
} finally {
PageHelper.clearPage();
}
} else {
list = new ArrayList<Country>();
}
这么写很不好看,而且没有必要。
4,结果
controller层中简单的调用然后返回json字符串如下:可以看出,结果基于doc_abstract排序后返回1-10条的数据