无名阁,只为技术而生。流水不争先,争的是滔滔不绝。

(mybatisplus selectpage) MybatisPlus中selectPage的使用方法 「MybatisPlus分页查询」 全网首发(图文详解1)

前沿技术 Micheal 3个月前 (06-22) 34次浏览 已收录 扫描二维码

(mybatisplus selectpage) MybatisPlus中selectPage的使用方法

MybatisPlus 是一个增强版的 Mybatis,它简化了很多繁琐的配置和操作,提高开发效率。在 MybatisPlus 中,selectPage 方法是用来进行分页查询的。接下来,我将详细介绍如何使用 selectPage 方法,并给出一个示例。

1. 添加 MybatisPlus 依赖

首先,确保你的项目中已经添加了 MybatisPlus 的依赖。如果没有,可以通过 Maven 添加:

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>最新版本号</version>
</dependency>

2. 配置 MybatisPlus

Spring Boot 项目的 application.yml 或者 application.properties 中进行 MybatisPlus 的相关配置,如数据源配置、分页插件配置等。

application.yml 示例:

mybatis-plus:
  mapper-locations: classpath:/mapper/*.xml
  global-config:
    db-config:
      id-type: auto
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

3. 实现分页

你需要定义一个 Mapper 接口,该接口继承 BaseMapper 接口。

public interface UserMapper extends BaseMapper<User> {
    // 这里不需要写任何方法,BaseMapper 已经包含了大量常用方法
}

使用 selectPage 方法实现分页查询:

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 分页查询用户
     *
     * @param current 当前页
     * @param size 每页数量
     * @return 分页对象
     */
    public IPage<User> selectUserPage(long current, long size){
        // 创建分页对象,传入当前页和每页显示条数
        Page<User> page = new Page<>(current, size);
        // 调用分页查询方法,无条件查询时,传入分页对象和 Wrappers.emptyWrapper() 即可
        return userMapper.selectPage(page, Wrappers.<User>lambdaQuery());
    }
}

4. 测试分页查询

在你的 Controller 中调用 UserService 中的 selectUserPage 方法进行分页查询的测试:

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/page")
    public IPage<User> getUserPage(@RequestParam(value = "current", defaultValue = "1") long current,
                                   @RequestParam(value = "size", defaultValue = "10") long size) {
        return userService.selectUserPage(current, size);
    }
}

这样,一个基于 MybatisPlus 的分页查询就完成了。你可以通过浏览器或者 Postman 工具访问 /user/page?current=1&size=10 来测试分页查询功能。
(vue computed set) Vue Computed中get和set的用法及Computed与watch的区别 Vue.js 中的计算属性 全网首发(图文详解1)
(cheatmaster) cheatmaster 金手指插件 官方版 CheatMaster金手指插件安装步骤 全网首发(图文详解1)

喜欢 (0)
[]
分享 (0)
关于作者:
流水不争先,争的是滔滔不绝