MybatisPlus内置分页插件快速使用
1.创建配置类
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
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;
@Configuration
@MapperScan("mapper接口包")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 向Mybatis过滤器链中添加分页拦截器
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
2.代码,实现条件分页查询
本例子为根据含有的关键字查询
1.controller
/**
*
* @param page 当前页
* @param limit 每页显示个数
* @param sysRoleQueryVo 查询数据条件
* @return 返回分页信息
*/
@GetMapping("/{page}/{limit}")
public Result findPageQueryRole(@PathVariable long page,
@PathVariable long limit,
SysRoleQueryVo sysRoleQueryVo) {
//创建page对象
Page<SysRole> PageParam = new Page<>(page, limit);
//调用service方法,获取分页信息
IPage<SysRole> pageModel = sysRoleService.selectPage(PageParam, sysRoleQueryVo);
//返回分页信息
return Result.ok(pageModel);
}
2.service
//条件分页查询
IPage<SysRole> selectPage(Page<SysRole> pageParam, SysRoleQueryVo sysRoleQueryVo);
3.serviceImpl
//条件分页查询
@Override
public IPage<SysRole> selectPage(Page<SysRole> pageParam, SysRoleQueryVo sysRoleQueryVo) {
IPage<SysRole> pageModel = baseMapper.selectPage(pageParam, sysRoleQueryVo);
return pageModel;
}
4.mapper
//条件分页查询
IPage<SysRole> selectPage(Page<SysRole> pageParam, @Param("vo") SysRoleQueryVo sysRoleQueryVo);
5.xml
<resultMap id="RoleMap" type="com.atguigu.model.system.SysRole" autoMapping="true">
</resultMap>
<!-- 用于select查询公用抽取的列 -->
<sql id="columns">
id,role_name,role_code,description,create_time,update_time,is_deleted
</sql>
<!--条件分页查询-->
<select id="selectPage" resultMap="RoleMap">
select <include refid="columns" /> from sys_role
<where>
<if test="vo.roleName != null and vo.roleName != ''">
and role_name like CONCAT('%',#{vo.roleName},'%')
</if>
and is_deleted = 0
</where>
order by id desc
</select>
6.测试
利用Swagger2测试结果
输入参数:
得到json数据:
{
"code": 200,
"message": "成功",
"data": {
"records": [
{
"id": "17",
"createTime": "2022-12-08 18:18:06",
"updateTime": "2022-12-08 18:18:06",
"isDeleted": 0,
"param": {},
"roleName": "测试角色",
"roleCode": "1232",
"description": null
},
{
"id": "16",
"createTime": "2022-12-04 15:54:54",
"updateTime": "2022-12-04 15:54:54",
"isDeleted": 0,
"param": {},
"roleName": "钟离",
"roleCode": "Lord Land",
"description": null
}
],
"total": 11,
"size": 2,
"current": 1,
"orders": [],
"optimizeCountSql": true,
"hitCount": false,
"countId": null,
"maxLimit": null,
"searchCount": true,
"pages": 6
}
}