【在Spring Boot中集成MyBatis-Plus实现分页】

MyBatis-Plus是MyBatis的增强工具,提供了一系列增强特性,包括分页查询。本文将详细介绍如何在Spring Boot项目中集成MyBatis-Plus,并利用其分页功能实现分页查询。

1. 项目依赖配置

首先,需要在pom.xml文件中添加MyBatis-Plus和MyBatis的依赖:

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

<!-- MyBatis -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>最新版本</version>
</dependency>

2. 数据源配置

在application.properties或application.yml中配置数据库连接信息:

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/your_database
    username: your_username
    password: your_password

3. MyBatis-Plus 配置

创建一个配置类,使用@MapperScan注解指定Mapper接口的扫描路径:

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@MapperScan("com.example.yourpackage.mapper")
public class MybatisPlusConfig {
    // 可以在此配置MyBatis-Plus的其他特性,如逻辑删除、自动填充等
}

4. 实体类和Mapper接口

创建实体类和对应的Mapper接口,使用@TableName注解指定表名,@TableId注解指定主键:

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

@Data
@TableName("user")
public class User {
    
    @TableId
    private Long id;
    private String username;
    private String email;
    // 其他字段...
}

import com.baomidou.mybatisplus.core.mapper.BaseMapper;

public interface UserMapper extends BaseMapper<User> {
    // 这里可以添加自定义的查询方法
}

5. 服务层和控制器

创建服务层和控制器,使用Page类实现分页查询:

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public PageUtils page(UserListReqVO reqVO) {
        IPage<User page = userMapper.selectPage(
                  new Page<>(reqVO.getPageIndex(), reqVO.getPageSize()), reqVO);
        return new PageUtils(page);
    }

}

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/usersPage")
    public AjaxResult getUsersByPage(@Valid UserListReqVO reqVO) {
        PageUtils list = amcDoorplateService.page(reqVO);
        return AjaxResult.Success("success",list);
    }
}

7.工具类

1) 返回信息 -AjaxResult


@Data
@Builder
public class AjaxResult<T> {

    public static class AjaxStatus {
        public static final Integer Info = 100; // token有误
        public static final Integer Success = 200; // 获取数据成功状态码
        public static final Integer ERROR = 300;    //	求失败
        public static final Integer Warning = 400; //
        public static final Integer UnAuthorized = 500; // 数据已存在

    }

    private Integer statusCode;   //返回码
    private String message; //回执信息
    private T data;    //回执数据


    public static AjaxResult Success(String msg, Object obj) {
        AjaxResult result = AjaxResult.builder().build();

        result.setStatusCode(AjaxStatus.Success);
        result.message = msg;
        result.data = obj;
        return result;
    }

    public static AjaxResult Error(Integer code, String msg) {
        AjaxResult result = AjaxResult.builder().build();
        result.setStatusCode(code);
        result.message = msg;
        return result;
    }


    public static AjaxResult Error(String msg) {
        AjaxResult result = AjaxResult.builder().build();
        result.setStatusCode(AjaxStatus.ERROR);
        result.message = msg;
//        new Exception().printStackTrace();
        return result;
    }

    public static void Error(HttpServletResponse response) {
        try {
            response.setStatus(AjaxStatus.ERROR);
            response.getOutputStream().close();
        } catch (Exception e) {

        }
    }

    public static AjaxResult UnAuthorized(String msg) {
        AjaxResult result = AjaxResult.builder().build();
        result.setStatusCode(AjaxStatus.UnAuthorized);
        result.setMessage(msg);
        result.setData("UnAuthorized");
        return result;
    }


}

2) 分页 信息 - PageUtils


public class    PageUtils implements Serializable {

    private static final long serialVersionUID = 1L;
    /**
     * 总记录数
     */
    private int totalCount;

    /**
     * 每页记录数
     */
    private int pageSize;

    /**
     * 总页数
     */
    private int totalPage;
    /**
     * 当前页数
     */
    private int currPage;
    /**
     * 列表数据
     */
    private List<?> list;

    /**
     * 分页
     * @param list        列表数据
     * @param totalCount  总记录数
     * @param pageSize    每页记录数
     * @param currPage    当前页数
     */
    public PageUtils(List<?> list, int totalCount, int pageSize, int currPage) {
        this.list = list;
        this.totalCount = totalCount;
        this.pageSize = pageSize;
        this.currPage = currPage;
        this.totalPage = (int)Math.ceil((double)totalCount/pageSize);
    }


    public PageUtils(List<?> list, long totalCount, long pageSize, long currPage) {
        this.list = list;
        this.totalCount = (int)totalCount;
        this.pageSize = (int)pageSize;
        this.currPage = (int)currPage;
        this.totalPage = (int)Math.ceil((double)totalCount/pageSize);
    }

    /**
     * 分页
     */
    public PageUtils(IPage<?> page) {
        this.list = page.getRecords();
        this.totalCount = (int)page.getTotal();
        this.pageSize = (int)page.getSize();
        this.currPage = (int)page.getCurrent();
        this.totalPage = (int)page.getPages();
    }

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public int getCurrPage() {
        return currPage;
    }

    public void setCurrPage(int currPage) {
        this.currPage = currPage;
    }

    public List<?> getList() {
        return list;
    }

    public void setList(List<?> list) {
        this.list = list;
    }
}

7. 测试

启动Spring Boot应用,访问/users接口即可进行分页查询:

curl http://localhost:8080/users


以上就是在Spring Boot中集成MyBatis-Plus实现分页查询的基本步骤。通过简单的配置和使用MyBatis-Plus提供的分页特性,可以轻松地在Spring Boot项目中实现分页查询功能。```

  • 23
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

無飞

叠码不易,鼓励鼓励。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值