【在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项目中实现分页查询功能。```

你可能感兴趣的:(spring,boot,mybatis,后端)