1.相关依赖:
<!-- mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<!-- 分页插件 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
<version>3.4.2</version>
</dependency>
2.写mybatis-plus的分页插件:
import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MybatisPlusConfig { /** * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除) */ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; } @Bean public ConfigurationCustomizer configurationCustomizer() { return configuration -> configuration.setUseDeprecatedExecutor(false); } }
设置好这个之后,就可以使用分页插件了
3.直接上代码
普通分页:
@PostMapping(value = "/getEmployeeLIst") public String insert(@RequestBody C c, HttpServletRequest request) throws Exception { // 创建条件构造器 QueryWrapper<DealerEmployeeModel> dealerEmployeeModelQueryWrapper = new QueryWrapper<>(); // 创建分页对象 Page<DealerEmployeeModel> dealerEmployeeModelPage = new Page<>(1,2); // 查询数据 dealerEmployeeMapper.selectPage(dealerEmployeeModelPage,dealerEmployeeModelQueryWrapper); // 获取集合 List<DealerEmployeeModel> records = dealerEmployeeModelPage.getRecords(); // 获取总数量 long total = dealerEmployeeModelPage.getTotal(); // 获取总页数 long pages = dealerEmployeeModelPage.getPages(); return successResult(records); }
xml文件分页:
@PostMapping(value = "/getEmployeeLIst") public String insert(@RequestBody C c, HttpServletRequest request) throws Exception { // 创建分页对象 Page<DealerEmployeeModel> dealerEmployeeModelPage = new Page<>(1,2); // 查询数据 List<DealerEmployeeModel> selectarr = dealerEmployeeMapper.selectarr(dealerEmployeeModelPage); // 获取总数量 long total = dealerEmployeeModelPage.getTotal(); // 获取总页数 long pages = dealerEmployeeModelPage.getPages(); return successResult(selectarr); }
在这里我直接定义了一个方法,查询的内容写在xml文件上:
List<DealerEmployeeModel> selectarr(Page<DealerEmployeeModel> dealerEmployeeModelPage);
<select id="selectarr" resultType="com.example.mp_pring.entity.DealerEmployeeModel"> select * from dealer_employee </select>
可以看到,我就只是单纯的进行一个查询,但是如果我们把page分页对象,放到接口方法的第一个参数上,就可以自动进行分页,至于结果我就不执行了,各位可以自己尝试一下,很简单的