当数据量很大时,我们需要按照分页处理,介绍接种分页方法
@Service public class Demo { @Autowired private UserMapper userMapper; /** * 方法1:原始mysql limit分页 * currentPage:当前页 * pageSize:每页记录数 * sql: select * from student limit(currentPage-1)*pageSize,pageSize; */ public void service1(){ int currentPage = 1; int pageSize = 10; List<User> list ; do{ list = userMapper.selectPage((currentPage-1)*pageSize,pageSize); currentPage++; handleList(list); }while (list.size() == pageSize); } /**方法2: * 当查询的表唯一列,并且此列有大小顺序的 * 利用此列查询 */ public void service2(){ int id = 0; int pageSize = 10; List<User> list; do{ list = userMapper.getPage(id, pageSize); if(list.size() >0){ id = list.get(list.size()-1).getId(); handleList(list); } }while (list.size() == pageSize); } /** *方法3: * 使用mybatis提供的 ResultContext 流处理 * 注:此方法并不是分页查询,只是讲一次查询的数据逐条处理 */ public void service3(){ final List<User> list = new ArrayList<>(); userMapper.queryIncreaseFetch(resultContext->{ // 这里查询出来多条数据 list.add(resultContext.getResultObject()); if(list.size()==3){ handleList(list); list.clear(); } }); if(list.size() > 0){ handleList(list); } } //业务模拟 public void handleList( List<User> users){ // 业务处理 可以结合多线程处理 users.forEach(System.out::println); } }
@Mapper public interface UserMapper { void queryIncreaseFetch(ResultHandler<User> userResultHandler); List<User> getPage(@Param("id")int id, @Param("pageSize")int pageSize); List<User> selectPage(@Param("currentPage") int currentPage,@Param("pageSize") int pageSize); }
xml文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.test.springboottest.dao.UserMapper"> <select id="queryIncreaseFetch" resultType="com.test.springboottest.entity.User"> select * from device_info limit 10 </select> <select id="getPage" resultType="com.test.springboottest.entity.User"> select * from device_info where id > #{id} order by id limit #{pageSize} </select> <select id="selectPage" resultType="com.test.springboottest.entity.User"> select * from device_info limit #{currentPage},#{pageSize}; </select> </mapper>
除了上面几种方法外,可以使用 pagehelper 插件