@Select("${sql}") List queryByCondition(@Param("sql") String sql);
1.2 编写IUserService.java
//分页查询 List queryAtPage(int page,int pageSize);
1.3 编写UserServiceImpl.java
@Override public List queryAtPage(int page, int pageSize) { //计算索引 int beginIndex =(page-1)*pageSize; //声明sql String sql="select * from user limit "+beginIndex+","+pageSize; //执行查询 List userList = this.userMapper.queryByCondition(sql); return userList; }
1.4 编写UserController.java
//分页查询 @RequestMapping(value="/queryByPage/{page}",method = RequestMethod.GET) public String queryAtPages(@PathVariable int page){ //执行的返回结果 Map map = new HashMap(); try{ List userList =userService.queryAtPage(1,2)//查看第1页,每页2条 if(userList!=null&&userList.size()>0){ map.put("status",200); map.put("data",userList); }else{ map.put("status",-1); map.put("message","没有检索到相关数据!"); } }catch (Exception ex){ map.put("status","500");//执行出现异常 map.put("message","异常信息:"+ex.getMessage()); } return JSON.toJSONString(map); }
//封装Page元素信息 public class PageInfo { private int nowPage; //当前页数 private int pageSize; //每页记录条数 private int totalNum; //总记录数 private int totalPage; //总页数 private List data; //当前页记录集合 //...setter等方法 }
2.2 编写UserMapper.java
//原生Sql方式查询信息集合 @Select("${sql}") List query(@Param("sql") String sql); //原生sql方式返回记录数 @Select("${sql}") int queryCount(@Param("sql") String sql);
@Override public PageInfo queryAtPage2(int page, int pageSize) { //分页sql String sql1="select name,age,address " + "from user u " + "inner join addressinfo a on u.id=a.uid " + "order by age DESC " + "limit "+(page-1)*pageSize+","+pageSize; //检索总记录数的sql String sql2="select count(*) count " + "from user u " + "inner join addressinfo a on u.id=a.uid"; //得到当前记录集合 List userList = this.userMapper.query(sql1); //得到总记录数 int totalCount = this.userMapper.queryCount(sql2); //得到总页数 int toalPage = totalCount%pageSize==0?totalCount/pageSize:totalCount/pageSize+1; //封装PageInfo实体bean PageInfo pageInfo = new PageInfo(page,pageSize,totalCount,toalPage,userList); return pageInfo; }