我们来模拟一个分页查询的案例:
假设数据库中有以下 Product
表的数据:
id | name | price |
---|---|---|
1 | iPhone 12 Pro | 1200 |
2 | iPad Air | 800 |
3 | MacBook Pro | 1500 |
4 | iPhone 11 | 1000 |
5 | iPhone 12 | 1100 |
6 | iPhone SE | 600 |
7 | iPhone 12 Mini | 900 |
8 | iPad Mini | 1300 |
9 | AirPods | 200 |
10 | Apple Watch | 300 |
11 | MacBook Air | 1200 |
12 | iPhone XR | 800 |
13 | iMac | 2500 |
14 | iPod Touch | 400 |
15 | HomePod | 350 |
16 | Magic Mouse | 100 |
17 | Apple Pencil | 150 |
18 | Apple TV | 180 |
19 | AirTag | 50 |
20 | Mac Mini | 700 |
现在我们要进行分页查询,每页显示 5 条记录,并按照价格字段降序排序,并且在控制台打印。
@Service
public class ProductService {
@Resource
private ProductMapper productMapper;
public IPage<Product> getProductListWithPage(int pageNum, int pageSize) {
Page<Product> page = new Page<>(pageNum, pageSize);
LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.orderByDesc(Product::getPrice); // 按价格字段降序排序
IPage<Product> productIPage = productMapper.selectPage(page, queryWrapper);
return productIPage;
}
public void printProducts(IPage<Product> productIPage) {
** //获取当前页的数据列表
List<Product> productList = productIPage.getRecords();**
for (Product product : productList) {
System.out.println("ID: " + product.getId() + ", Name: " + product.getName() + ", Price: " + product.getPrice());
}
}
}
假设我们调用 getProductListWithPage(1, 5)
方法,表示查询第一页,每页显示 5 条记录。
id | name | price |
---|---|---|
13 | iMac | 2500 |
3 | MacBook Pro | 1500 |
8 | iPad Mini | 1300 |
1 | iPhone 12 Pro | 1200 |
11 | MacBook Air | 1200 |
这个时候IPage的值为
List<Product> records
:当前页的数据列表,共有 5 条记录。这些记录是满足查询条件的第一页数据,即价格最高的五个产品记录。long total
:总记录数,共有 20 条记录满足查询条件。这个值表示满足查询条件的总记录数。long size
:每页显示的记录数,每页显示 5 条记录。这个值表示每页显示的记录数,是传入getProductListWithPage
方法时指定的每页大小。long current
:当前页码,查询的是第一页,即 current 为 1。这个值表示当前查询的页码,是传入getProductListWithPage
方法时指定的页码。long pages
:总页数,由于总记录数是 20 条,每页显示 5 条记录,所以总页数为 4。这个值表示满足查询条件的总页数,是根据总记录数和每页显示的记录数计算得出的。boolean searchCount
:是否进行 count 查询,为 true。这个值表示是否查询总记录数,在getProductListWithPage
方法中默认为 true,即进行查询。boolean optimizeCountSql
:是否优化 count SQL,为 true。这个值表示是否优化 count SQL,在getProductListWithPage
方法中默认为 true,即进行优化。
所以,当执行 getProductListWithPage(1, 5)
方法时,IPage<Product>
对象 productIPage
中的各个属性值为:
**List<Product> records = productIPage.getRecords(); // 获取当前页的数据列表,共有 5 条记录
**long total = productIPage.getTotal(); // 总记录数,共有 20 条记录满足查询条件
long size = productIPage.getSize(); // 每页显示的记录数,每页显示 5 条记录
long current = productIPage.getCurrent(); // 当前页码,查询的是第一页,即 current 为 1
long pages = productIPage.getPages(); // 总页数,由于总记录数是 20 条,每页显示 5 条记录,所以总页数为 4
boolean searchCount = productIPage.isSearchCount(); // 是否进行 count 查询,为 true
boolean optimizeCountSql = productIPage.optimizeCountSql(); // 是否优化 count SQL,为 true