后端使用分页插件实现分页查询代码
时间: 2024-05-10 21:15:27 浏览: 7
假设你使用的是 Java Spring Boot 框架,可以使用 MyBatis 分页插件进行分页查询。
首先,在 pom.xml 中添加 MyBatis 分页插件的依赖:
```xml
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
```
然后,在需要进行分页查询的方法中,调用 PageHelper.startPage() 方法开启分页功能,并传入当前页码和每页显示的数据条数,如下所示:
```java
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public PageInfo<User> getUsers(int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<User> users = userMapper.getUsers();
return new PageInfo<>(users);
}
}
```
在上面的代码中,我们调用了 PageHelper.startPage() 方法开启分页功能,并传入了当前页码和每页显示的数据条数。然后,我们调用 UserMapper 接口中的 getUsers() 方法来获取所有用户数据,并将其封装成 PageInfo 对象返回。
最后,我们可以在控制器中调用 getUsers() 方法来获取分页数据,并将其返回给前端页面显示,如下所示:
```java
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users")
public PageInfo<User> getUsers(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "10") int pageSize) {
return userService.getUsers(pageNum, pageSize);
}
}
```
在上面的代码中,我们使用 @GetMapping 注解来处理 GET 请求,并通过 @RequestParam 注解来获取请求参数中的当前页码和每页显示的数据条数。然后,我们调用 UserService 接口中的 getUsers() 方法来获取分页数据,并将其返回给前端页面显示。
至此,我们就完成了后端使用分页插件实现分页查询的代码编写。