簡易的分頁查詢,業務層代碼(自用,想到啥寫啥)
@Service
public class ItemServiceImpl implements ItemService {
@Autowired
private ItemMapper itemMapper;
/**
* 分頁查詢數據
*/
@Override
public EasyUITable findItemByPage(Integer page, Integer rows) {
//1.手寫分頁
int total = itemMapper.selectCount(null); //查詢總記錄數
/**
* sql:
* select * from tb_item limit 起始位置,查詢記錄數 每頁20條
* 第一頁:
* select * from tb_item limit 0,20; index:0-19 第21條沒有取
* 第二頁:
* select * from tb_item limit 20,20;
* 第三頁
* select * from tb_item limit 40,20;
* 第N頁
* select * from tb_item limit (page-1)rows,rows;
*/
int start = (page - 1) * rows; //定義起始位置
List<Item> itemList = itemMapper.findItemByPage(start,rows);
return new EasyUITable(total, itemList);
}
在Mybatis_Plus的mapper接口中
public interface ItemMapper extends BaseMapper<Item>{
/**
* 高版本中可以省略@Param註解,參數名稱必須一致.
* @param start
* @param rows
* @return
*/
@Select("SELECT * FROM tb_item ORDER BY updated DESC LIMIT #{start},#{rows}")
List<Item> findItemByPage(int start,Integer rows);
}
當然Mybatis_Plus中也有內置的分頁功能的實現
1.需要通過分頁攔截器
@Configuration //配置類就是xml配置文件
public class MPConfig {
//MP分頁操作需要通過MP分頁攔截器才能生效
@Bean //實例化對象交給spring容器管理
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
2.業務層實現
/**
* 分頁查詢數據
*/
@Override
public EasyUITable findItemByPage(Integer page, Integer rows) {
//2.利用MP方式實現分頁查詢
IPage<Item> iPage = new Page<>(page, rows); //查詢頁數和條數
QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
queryWrapper.orderByDesc("updated");
IPage<Item> resultPage = itemMapper.selectPage(iPage, queryWrapper);
//查詢總頁數
int total = (int) resultPage.getTotal();
//查詢分頁信息
List<Item> itemList = resultPage.getRecords();
return new EasyUITable(total, itemList);
}