使用过mybatis的人都知道,mybatis本身就很小且简单,sql写在xml里,统一管理和优化。缺点当然也有,比如我们使用过程中,要使用到分页,如果用最原始的方式的话,1.查询分页数据,2.获取分页长度,也就是说要使用到两个方法才能完成分页。有没有更更好的分页方式的,pagehelper分页插件因此而诞生,他的原理是利用mybatis拦截器,在查询数据库的时候,拦截下SQL,然后进行修改,从而实现分页(如果你硬是想知道原理,mybatis拦截器,学习过后你就知道什么回事了)。
这篇博客先向大家展示怎么使用,过后有时间再讲他的实现原理。
1.添加maven依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.0.0</version>
</dependency>
2.在 Spring 配置文件中配置拦截器插件,也可以在mybatis的xml里面配置,但是两种配置不能同时出现,否则容易出现com.github.pagehelper.PageInterceptor插件出现空指针问题
在spring.xml中定义:
<!--配置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>
在mybatis-config.xml中定义
<plugins>
<!-- com.github.pagehelper为PageHelper类所在包名 -->
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!-- 使用MySQL方言的分页 -->
<property name="helperDialect" value="sqlserver"/><!--如果使用mysql,这里value为mysql-->
<property name="pageSizeZero" value="true"/>
</plugin>
</plugins>
3.使用
1.写正常查询语句的接口
<select id="findUser" parameterType="User">
select * from user
</select>
2.接口:
/**
* 查询所有User
*/
List<User> findUser()
3.在service层调用接口,实现分页。
//分页
@RequestMapping("part/findAllDept.do")
@ResponseBody
public Msg findAllDept(@RequestParam(value="pageNo",defaultValue="1" Integer pageNo,
@RequestParam(value="pageSize",defaultValue="10") Integer pageSize){
PageHelper.startPage(pageNo, pageSize);
//startPage后面紧跟的这个查询就是一个分页查询
List<User> list = mydeptService.findUser();
//使用pageInfo包装查询后的结果,只需要将pageInfo交给页面就行了。
PageInfo<User> pa = new PageInfo<User>(list);
return new Msg(200,"cg").add("list", pa);
}
到此结束,有用点赞哦!!!!!扎扎楠