分页查询时,一次性查询分页数据和总数量,而不是分两次查询。
1,Mapper.xml文件配置
<resultMap id="beanMap" type="com.gx.pojo.DeptVo"> <result column="deptNo" property="deptNo"></result> <result column="deptName" property="deptName"></result> </resultMap> <resultMap id="count" type="java.lang.Integer"> <result column="total"/> </resultMap> <select id="getAll" parameterType="java.util.Map" resultMap="beanMap,count"> select SQL_CALC_FOUND_ROWS * from dept order by deptNo limit #{pageStart},#{pageSize}; select FOUND_ROWS() as total; </select>
sql语句上使用SQL_CALC_FOUND_ROWS和SELECT FOUND_ROWS AS total,可以查询数据列表的同时查询总数。
2,Dao代码
public interface DeptMapper { List<Object> getAll(Map<String,Object> map); }
3,测试
@Test public void getDeptList(){ DeptMapper mapper = sqlSession.getMapper(DeptMapper.class); Map<String,Object> map=new HashMap<>(); map.put("pageStart",0); map.put("pageSize",3); List<Object> all = mapper.getAll(map); List<DeptVo> list =(List<DeptVo>) all.get(0); Integer total =(Integer)((List<Object>)all.get(1)).get(0); list.forEach(System.out::println); System.out.println(total); sqlSession.close(); }
3,需要注意的是在mysql连接字符串url上需配置allowMultiQueries=true
posted on
浙公网安备 33010602011771号