Mybatis Plus分页官网:https://mp.baomidou.com/guide/page.html
1.在已具备Mybatis功能后,Spring Boot配置文件添加配置
application.yml
mybatis-plus:
mapper-locations: classpath:mapping/*.xml
type-aliases-package: com.cx.mybatis.bean
# 日志打印,能显示SQL语句及结果之类的
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
2.添加MybatisPlusConfig配置类
MybatisPlusConfig
@Configuration
@MapperScan("com.cx.mybatis.mapper")
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false
// paginationInterceptor.setOverflow(false);
// 设置最大单页限制数量,默认 500 条,-1 不受限制
// paginationInterceptor.setLimit(500);
// 开启 count 的 join 优化,只针对部分 left join
paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
return paginationInterceptor;
}
}
3.数据库表及bean类
User表
CREATE TABLE `NewTable` (
`id` int(11) NOT NULL AUTO_INCREMENT ,
`username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
`role_id` int(11) NULL DEFAULT NULL ,
`createtime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ,
PRIMARY KEY (`id`)
)
ENGINE=InnoDB
DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci
AUTO_INCREMENT=13
ROW_FORMAT=DYNAMIC
User类
@TableName("t_user") // 数据库表格名称
public class User {
/**
* value 对应数据库表格中主键的字段名称
* type IdType.AUTO枚举类,意味对应数据库中的主键自动增长
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String username;
private String password;
private Integer roleId;
private Date createtime;
// 省略...
}
4.添加映射类及配置文件
UserMapper映射类
public interface UserMapper extends BaseMapper<User> {
/**
* 分页显示
* @param page 分页对象,xml中可以从里面进行取值,传递参数
* @return
*/
IPage<User> selectPage(Page page);
}
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.cx.mybatis.mapper.UserMapper">
<select id="selectPage" resultType="User">
select * from t_user
</select>
</mapper>
5.测试功能
UserTest测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserTest {
@Autowired
UserMapper userMapper;
@Test
public void test03() {
Page page = new Page();
// 设置页码
page.setCurrent(2);
// 设置显示条数
page.setSize(3);
IPage<User> iPage = userMapper.selectPage(page);
// 获取分页后的集合对象
List<User> userList = iPage.getRecords();
for (User user : userList) {
System.out.println(user);
}
}
}
显示结果