在大家平时写sql时,有时没有考虑到分页或者不会使用分页以及嫌麻烦的程序员们可以使用这个拦截器去实现分页的功能。
首先需要导jar包,在pom.xml中加入依赖:
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.6</version>
</dependency>
在jar包这要导入5.0以下的包,不然会报错。
首先在Spring的配置文件中配置SqlSessionFactory时,在它的里边还有一个属性是plugins我们可以给它配置拦截器:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation"
value="classpath:mybatis-config.xml" />
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageHelper">
<property name="properties">
<props>
<prop key="dialect">mysql</prop>
</props>
</property>
</bean>
</array>
</property>
</bean>
到目前为止咱们的配置就已经完成,可以去测试:
测试代码:
数据库:
dao:
/**
* 测试
*/
public List<Map<String,Object>> test();
mapper.xml中:
<select id="test" resultType="Map">
select * from user
</select>
Service接口:
public List<Map<String,Object>> test();
ServiceImpl:
public List<Map<String,Object>> test(){
List<Map<String,Object>> list = mapper.test();
return list;
}
Junit测试:
@Test
public void page() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:applicationContext-mybatis.xml");
CargoBillsService service = (CargoBillsService) ctx.getBean("cargoBillsServiceImpl");
PageHelper.startPage(1, 3);
List<Map<String,Object>> list = service.test();
System.out.println(list.size());
for(int i = 0;i<list.size();i++) {
System.out.print("[");
System.out.println(list.get(i));
System.out.println("]");
}
}
控制台:
3
[{regtime=2018-12-04 00:00:00.0, sex=1, usermoney=1, userid=111, delete=1, user_lv_id=1, validataCode=1, point=1, password=1, sfzh=1, phone=1, name=1, order_num=1, timeDate=2018-12-26 15:19:42.0, email=1, username=1, member_refer=1}
]
[{regtime=2018-11-14 00:00:00.0, sex=2, usermoney=2, userid=222, delete=-1, user_lv_id=2, validataCode=2, point=2, password=2, sfzh=2, phone=2, name=2, order_num=2, timeDate=2018-12-20 15:20:21.0, email=2, username=2, member_refer=-1}
]
[{regtime=2018-12-06 00:00:00.0, sex=3, usermoney=3, userid=333, delete=1, user_lv_id=3, validataCode=3, point=3, password=3, sfzh=3, phone=3, name=3, order_num=3, timeDate=2018-12-26 15:20:39.0, email=3, username=3, member_refer=1}
]