mybatisplus 不用分页插件为什么也会先count一次
时间: 2023-09-05 09:07:41 浏览: 63
MybatisPlus默认开启了分页插件,如果不需要分页功能,可以在MybatisPlus的配置文件中进行配置:
```
mybatis-plus:
configuration:
# 是否开启分页插件
page-helper:
enable: false
```
如果开启了分页插件,无论是否使用分页功能,都会先执行一次count查询来获取总记录数。这是因为分页插件需要知道总记录数才能计算出总页数,从而实现分页功能。如果不需要分页功能,可以禁用分页插件来避免这种情况。
相关问题
mybatisplus 可以只开分页插件 不开count吗
是的,MyBatis Plus分页插件提供了两种分页方式:基于 count 查询和不基于 count 查询。默认情况下,分页插件开启了基于 count 的分页查询,即在执行分页查询时,会先执行一次查询获取总记录数,然后再执行一次带有分页参数的查询获取分页数据。
如果你只需要分页数据而不需要总记录数,可以通过配置来关闭基于 count 的分页查询,只开启不基于 count 的分页查询。具体来说,你可以在 MyBatis 配置文件中配置 `dialectType` 属性,将其设置为 `noCount`,即可只开启不基于 count 的分页查询。例如:
```xml
<!-- MyBatis Plus 分页插件配置 -->
<plugins>
<plugin interceptor="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor">
<property name="dialectType" value="noCount"/>
</plugin>
</plugins>
```
这样配置后,MyBatis Plus 将只执行一次带有分页参数的查询获取分页数据,而不会执行获取总记录数的查询。
SpringBoot整合MybatisPlus 实现分页查询
SpringBoot整合MybatisPlus可以很方便地实现分页查询,而MybatisPlus本身也提供了物理分页的功能。下面是实现步骤:
1.在pom.xml文件中添加MybatisPlus和分页插件的依赖。
2.在application.yml文件中配置分页插件。
3.在Mapper接口中添加分页查询方法,使用MybatisPlus提供的Page对象进行分页查询。
4.在Service层中调用Mapper接口中的分页查询方法,将查询结果封装到Page对象中返回给Controller层。
5.在Controller层中接收前端传来的分页参数,调用Service层中的分页查询方法,将查询结果返回给前端。
具体实现代码可以参考以下示例:
1.在pom.xml文件中添加MybatisPlus和分页插件的依赖:
```
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
```
2.在application.yml文件中配置分页插件:
```
mybatis-plus:
configuration:
# 开启驼峰命名转换
map-underscore-to-camel-case: true
# 配置分页插件
plugins:
- com.github.pagehelper.PageInterceptor
# 配置分页插件的参数
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
```
3.在Mapper接口中添加分页查询方法,使用MybatisPlus提供的Page对象进行分页查询:
```
public interface UserMapper extends BaseMapper<User> {
/**
* 分页查询用户列表
* @param page 分页参数
* @return 用户列表
*/
List<User> selectUserList(Page<User> page);
}
```
4.在Service层中调用Mapper接口中的分页查询方法,将查询结果封装到Page对象中返回给Controller层:
```
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public Page<User> getUserList(Page<User> page) {
return userMapper.selectUserList(page);
}
}
```
5.在Controller层中接收前端传来的分页参数,调用Service层中的分页查询方法,将查询结果返回给前端:
```
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/list")
public Result getUserList(@RequestParam(defaultValue = "1") Integer pageNum,
@RequestParam(defaultValue = "10") Integer pageSize) {
Page<User> page = new Page<>(pageNum, pageSize);
Page<User> userList = userService.getUserList(page);
return Result.success(userList);
}
}
```