用mp怎么实现
时间: 2023-07-11 12:23:03 浏览: 65
使用 MyBatis-Plus(简称 MP)实现分页查询非常方便,只需要在查询方法中调用 PageHelper 的静态方法即可。
假设我们有一个实体类 User,对应数据库表名为 user,现在需要查询 user 表中的数据并分页显示,可以按照以下步骤实现:
1. 在 pom.xml 中引入 mybatis-plus-boot-starter 和 pagehelper 的依赖:
```xml
<!-- MyBatis-Plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.1</version>
</dependency>
<!-- PageHelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
```
2. 在 UserMapper 中添加查询方法:
```java
public interface UserMapper extends BaseMapper<User> {
@Select("SELECT * FROM user")
List<User> selectAll(Page<User> page);
}
```
其中,@Select 注解中的 SQL 语句可以根据实际情况修改。
3. 在 Service 层中调用查询方法:
```java
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Override
public List<User> findAll(Integer pageNum, Integer pageSize) {
Page<User> page = new Page<>(pageNum, pageSize);
return baseMapper.selectAll(page);
}
}
```
在 ServiceImpl 中,我们创建了一个 Page 对象,并将 pageNum 和 pageSize 作为参数传入。然后,在调用 selectAll 方法时,将该 Page 对象作为参数传入,MyBatis-Plus 会自动将分页信息封装到该对象中。
4. 在 Controller 中调用 Service 方法:
```java
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public List<User> findAll(@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
return userService.findAll(pageNum, pageSize);
}
}
```
在 Controller 中,我们通过 @RequestParam 注解获取请求中的 pageNum 和 pageSize 参数,并将其传递给 Service 方法。
这样,我们就完成了基于 MyBatis-Plus 和 PageHelper 的分页查询实现。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)