mybatisPlus-分页查询
添加分页插件
import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @MapperScan(basePackages = "com.atguigu.mapper") @Configuration public class Mpconfig { //乐观锁插件 @Bean public MybatisPlusInterceptor mybatisPlusInterceptor(){ //1 创建MybatisPlusInterceptor拦截器对象 MybatisPlusInterceptor mpInterceptor=new MybatisPlusInterceptor(); //添加分页插件,3.4.0之后版本 mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return mpInterceptor; } }
测试代码
@Test public void queryUserList(){ Page<User> page = new Page<>(2,3); userMapper.selectPage(page, null); System.out.println("当前页数据:"+page.getRecords()); System.out.println("总分页数量:"+page.getPages()); System.out.println("总记录数量:"+page.getTotal()); System.out.println("是否有下一页:"+page.hasNext()); System.out.println("是否有上一页:"+page.hasPrevious()); }
自定义分页功能
UserMapper接口
package com.atguigu.mapper; import com.atguigu.entity.User; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; @Repository public interface UserMapper extends BaseMapper<User> { //注意:mybatis-plus提供的分页对象,必须位于第一个参数的位置。 Page<User> selectAllUser(@Param("page") Page<User> page,@Param("age") int age); }
UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.atguigu.mapper.UserMapper"> <select id="selectAllUser" resultType="com.atguigu.entity.User"> select * from user where age > #{age} </select> </mapper>
测试代码
@Test public void test1(){ Page<User> page = new Page<>(2,3); userMapper.selectAllUser(page,20); System.out.println(page.getRecords()); }