1. pom.xml配置
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
2. 向Spring容器中注入PageHelper
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
@Configuration
public class PageHelperConfiguration {
private static final Logger log = LoggerFactory.getLogger(PageHelperConfiguration.class);
@Bean
public PageHelper pageHelper() {
log.info("------Register MyBatis PageHelper");
PageHelper pageHelper = new PageHelper();
Properties p = new Properties();
p.setProperty("offsetAsPageNum", "true");
p.setProperty("rowBoundsWithCount", "true");
p.setProperty("reasonable", "true");
//通过设置pageSize=0或者RowBounds.limit = 0就会查询出全部的结果。
p.setProperty("pageSizeZero", "true");
pageHelper.setProperties(p);
return pageHelper;
}
}
3. 在代码中使用PageHelper
@RestController
@RequestMapping("zz")
public class StuController {
@Autowired
StuService stuService;
//没写死
@RequestMapping("/query/{page}/{pageSize}")
public PageInfo query(@PathVariable Integer page, @PathVariable Integer pageSize) {
if(page!= null && pageSize!= null){
PageHelper.startPage(page, pageSize);
}
List<Student> users = stuService.list();
return new PageInfo(users);
}
//写死了
@RequestMapping(value = "users2", method = RequestMethod.GET)
public PageInfo<Student> queryAll( @RequestParam(value = "pageNum", required = false, defaultValue="1") Integer pageNum,
@RequestParam(value = "pageSize", required = false, defaultValue="6") Integer pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<Student> list = stuService.list();
PageInfo<Student> pageInfo = new PageInfo<Student>(list);
return pageInfo;
}
ps:
public interface StuService {
Student selectByPrimaryKey(Integer id);
List<Student> list(); // 代码由mybatis逆向工程自动生成.
}
访问验证
http://localhost:8788/zz/query/1/3