簡單描述:需求說后端寫一個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){
PageInfo<CourseVo> pageInfo = new PageInfo<CourseVo>();
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 PageInfo<CourseVo> queryPage(Integer page,Integer rows)throws Exception{
Map<String,Integer> param = new HashMap<String,Object>();
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<CourseVo> reList = courseMapper.findByPage(param);
// 取分頁信息
PageInfo<CourseVo> pageInfo = new PageInfo<CourseVo>(reList);
return pageInfo;
}
}
//Mapper接口
import com.xx.xxx.xxxx.util.MyMapper;
import java.util.List;
import java.util.Map;
public interface CourseMapper extends MyMapper<Course> {
List<CourseVo> findByPage(Map<String,Integer> param);
}
//Mapper.xml中的sql
<select id="findByPage" parameterType="Map" resultMap="CourseVoResultMap">
select * from table_course where is_del = '1' limit #{page},#{rows}
</select>
<resultMap id="CourseVoResultMap" type="CourseVo" >
<result column="course_id" property="courseId" jdbcType="CHAR" />
<result column="course_code" property="courseCode" jdbcType="VARCHAR" />
``````
</result>
That's all !!! 下邊來說一說PageHelper的方式
//僅僅是調用就OJBK啦 不過這種查詢方式使用的是mybatis的example動態生成sql查詢的,不需要你寫mapper.xml中的sql了,只需要在對應的類上加上注解
public PageInfo<CourseVo> queryPage(Integer page,Integer rows)throws Exception{
Example example = new Example(CourseVo.class);
example.createCriteria().andEqualTo("isDel", 1);
PageHelper.startPage(page, rows);
List<CourseVo> list = courseMapper.selectByExample(example);//查詢
return pageInfo;
}