简单描述:需求说后端写一个XX数据的分页接口,给前端口调用,其实有一个PageHelper的工具类可以直接使用但是老大不让用,得用sql写,。小Kiss啦。直接上代码
代码:
//Controller代码 import com.github.pagehelper.PageInfo; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @Api(value = "CourseController",tags = "课程查询") @RestController @RequestMapping("/client/course") public class CourseController extends BaseController { @Autowired private CourseService courseService; @ApiOperation(value = "获取分页列表") @RequestMapping(value = "/queryPage", method = RequestMethod.GET, produces = "application/json;charset=utf-8") public ResultDto queryPage(Integer page,Integer rows,String categoryId){ PageInfopageInfo = new PageInfo (); try { pageInfo = courseService.queryPage(page,rows); if(pageInfo.getList().size()< 0){ return ResultDto.success("返回结果无内容"); } } catch (Exception e) { e.printStackTrace(); return ResultDto.error(); } return ResultDto.success(pageInfo); } }
//Service代码 import com.github.pagehelper.PageInfo; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.HashMap; import java.util.List; import java.util.Map; @Service public class CourseService { @Resource private CourseMapper courseMapper; public PageInfoqueryPage(Integer page,Integer rows)throws Exception{ Map param = new HashMap (); Integer firstIndex = (page - 1) * rows; Integer lastIndex = page * rows; // 从第几条数据开始 int firstIndex = (currPage - 1) * pageSize; // 到第几条数据结束 int lastIndex = currPage * pageSize; param.put("page",firstIndex); param.put("rows",lastIndex); List reList = courseMapper.findByPage(param); // 取分页信息 PageInfo pageInfo = new PageInfo (reList); return pageInfo; } }
//Mapper接口 import com.xx.xxx.xxxx.util.MyMapper; import java.util.List; import java.util.Map; public interface CourseMapper extends MyMapper{ List findByPage(Map param); } //Mapper.xml中的sql ``````
That's all !!! 下边来说一说PageHelper的方式
//仅仅是调用就OJBK啦 不过这种查询方式使用的是mybatis的example动态生成sql查询的,不需要你写mapper.xml中的sql了,只需要在对应的类上加上注解 public PageInfoqueryPage(Integer page,Integer rows)throws Exception{ Example example = new Example(CourseVo.class); example.createCriteria().andEqualTo("isDel", 1); PageHelper.startPage(page, rows); List list = courseMapper.selectByExample(example);//查询 return pageInfo; }