MyBatis-Plus 插件——分页插件
添加配置类
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//添加分页插件
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
测试
@Test
public void testPagination() {
//设置分页参数
Page<User> page = new Page<>(1, 5);
userMapper.selectPage(page, null);
//获取分页参数
List<User> records = page.getRecords();
records.forEach(System.out::println);
System.out.println("当前页:"+page.getCurrent());
System.out.println("每页显示的条数:"+page.getSize());
System.out.println("总记录数:"+page.getTotal());
System.out.println("总页数:"+page.getPages());
System.out.println("是否有上一页:"+page.hasPrevious());
System.out.println("是否有下一页:"+page.hasNext());
}
结果:
User(id=4, name=admin, age=18, email=user@atguigu.com)
User(id=5, name=张三, age=18, email=test5@baomidou.com)
当前页:1
每页显示的条数:5
总记录数:2
总页数:1
是否有上一页:false
是否有下一页:false
自定义xml使用分页插件
UserMapper.java
/**
* 根据年龄分页查询对象
* @param page
* @param age
* @return
*/
Page<User> listPageByAge(Page<User> page, Integer 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.example.mapper.UserMapper">
<select id="listPageByAge" resultType="com.example.domain.User">
select u.id,u.name,u.age,u.email from t_user u where u.age=#{age}
</select>
</mapper>
测试:
@Test
public void testOwnerXml() {
Page<User> page = new Page<>(1, 5);
userMapper.listPageByAge(page, 20);
//获取分页参数
List<User> records = page.getRecords();
records.forEach(System.out::println);
System.out.println("当前页:"+page.getCurrent());
System.out.println("每页显示的条数:"+page.getSize());
System.out.println("总记录数:"+page.getTotal());
System.out.println("总页数:"+page.getPages());
System.out.println("是否有上一页:"+page.hasPrevious());
System.out.println("是否有下一页:"+page.hasNext());
}
结果:
User(id=5, name=张三, age=20, email=test5@baomidou.com)
当前页:1
每页显示的条数:5
总记录数:1
总页数:1
是否有上一页:false
是否有下一页:false