有啥问题欢迎指正和共同学习
1.首先需要装载依赖 ,二者选其一即可
//这里用的是mybatis-plus
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
//这里还有另一种方式选择
<!--pageHelperׁ-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
public class Diary implements Serializable {
private static final long serialVersionUID = -219988432063763456L;
public Diary(){}
private String name;
private String bytxt;
private String mobilefour;
//下面省略get set
}
@RestController
public class testcontroller {
/**
* 分页插件查询
*
* 请求地址 : http://localhost:8090/t5?currentPage=2&pageSize=3 端口号需替换成自己配的
* @param request :请求分页参数 currentPage 起始页, pageSize 页面展示数
**/
@RequestMapping("t5")
public String queryUserForPage(HttpServletRequest request) {
//获取前端传来的参数值
int currentPage = Integer.parseInt(request.getParameter("currentPage"));
int pageSize = Integer.parseInt(request.getParameter("pageSize"));
//int currentPage = 2; //起始页
//int pageSize = 3; //页面展示数
//获取config中配置的信息 (也可通过注入Dao的方式)
SqlSessionFactory bean = (SqlSessionFactory) applicationContext.getBean("testSqlSessionFactory");
SqlSession sqlSession = bean.openSession();
try {
//rowBounds需要的第一个参数就是从数据的哪个下标开始开始查,第二个就是你需要查询的条数
RowBounds rowBounds = new RowBounds((currentPage - 1) * pageSize, pageSize);
//方法的全路径, 传入的参数, rowBounds
List<Diary> list = sqlSession.selectList("com.example.plus.dao.DiaryMapper.getAllRowBounds", null, rowBounds);
//遍历打印对象中的name
list.forEach(e -> System.out.println(e.getName()));
} catch (Exception e) {
new RuntimeException();
return "FAIL";
} finally {
sqlSession.close();
}
return "SUCCESS";
}
@RequestMapping("page")
public void page() {
SqlSessionFactory bean = (SqlSessionFactory) applicationContext.getBean("testSqlSessionFactory");
SqlSession sqlSession = bean.openSession();
try {
//执行分页
PageHelper.startPage(1, 5);
//执行查询
List<Diary> list = sqlSession.selectList("com.example.plus.dao.DiaryMapper.getAllRowBounds");
//封装pageInfo对象
PageInfo<Diary> pageInfo = new PageInfo<>(list);
//输出
for (Diary diary : pageInfo.getList()) {
System.out.println(diary.getName() + " " + diary.getMobilefour() + " " + diary.getBytxt() + "\r\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
}
}
<select id="getAllRowBounds" resultType="com.example.plus.pojo.Diary">
SELECT * FROM diary
</select>