1、分页
官方文档https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md
1.1 配置
pom.xml
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>最新版本</version>
</dependency>
在mybatis中配置分页
<plugins>
<!-- com.github.pagehelper为PageHelper类所在包名 -->
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!-- 使用下面的方式配置参数-->
<!-- <property name="param1" value="value1"/> -->
</plugin>
</plugins>
或者在spring配置中配置分页:spring管理mybatis的sqlsessionfactory,在该配置中添加分页插件
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注意其他配置 -->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<!--使用下面的方式配置参数,一行配置一个 -->
<value>
params=value1
</value>
</property>
</bean>
</array>
</property>
</bean>
1.2 分页的使用
在controller类中使用分页,将分页发送到页面
@RequestMapping("/getAllEmployees")
public String getAllEmployees(
@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize", required = false, defaultValue = "100") Integer pageSize,
Map<String, Object> map) {
//在查询方法之前调用
PageHelper.startPage(pageNum, pageSize);
List<Employee> allEmployee = employeeService.getAllEmployee();
//使用pageinfo对象,该对象中可以得到分页所有数据
PageInfo<Employee> info = new PageInfo<>(allEmployee,5);
map.put("list",info);
return "list";
}
PageInfo包含了非常全面的分页属性
assertEquals(1, page.getPageNum());
assertEquals(10, page.getPageSize());
assertEquals(1, page.getStartRow());
assertEquals(10, page.getEndRow());
assertEquals(183, page.getTotal());
assertEquals(19, page.getPages());
assertEquals(1, page.getFirstPage());
assertEquals(8, page.getLastPage());
assertEquals(true, page.isFirstPage());
assertEquals(false, page.isLastPage());
assertEquals(false, page.isHasPreviousPage());
assertEquals(true, page.isHasNextPage());
2、MockMvc测试controller类
RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "classpath:/spring/spring-context.xml", "classpath:/spring/springmvc-config.xml"})
public class TestEmployeeController {
@Autowired
WebApplicationContext context;//
MockMvc mockMvc;
@Before
public void init(){
//获取mockmvc对象
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
@Test
public void test1() throws Exception {
//调用getAllEmployees方法并传参,再获取返回值
MvcResult result = mockMvc
.perform(MockMvcRequestBuilders.get("/getAllEmployees").param("pageNum", "2").param("pageSize", "500"))
.andReturn();
//从request域中获取对象并转成目标对象
PageInfo<Employee> info = (PageInfo<Employee>) result.getRequest().getAttribute("list");
System.out.println(info.getPageNum());
System.out.println(info.getPageSize());
System.out.println(info.getTotal());
//pageinfo对象方法getList()获取封装的list对象
int size = info.getList().size();
System.out.println(size);
}
ps:ContextConfiguration中的两个参数分别用于获取spring容器和dispatcherservlet(前端控制器,用于找到mapping对应的controller方法)