SpringBoot系列之MongoDB分页接口实现

2022-12-01 15:37:41 浏览数 (2)

SpringBoot系列之MongoDB分页接口实现

spring-boot-starter-data-mongodb也有集成基于Spring Data的分页实现,但是习惯了用PageHelper,所以基于PageHelper集成一下mongodb,下面给出实现代码例子

环境准备

  • 开发环境
    • JDK 1.8
    • SpringBoot2.2.1
    • Maven 3.2
  • 开发工具
    • IntelliJ IDEA
    • smartGit
    • Navicat15

Maven配置

新建一个SpringBoot下面,在pom配置文件里加上,dependencyManagement进行Springboot统一的版本控制

代码语言:javascript复制
<properties>
    <java.version>1.8</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <spring-boot.version>2.2.1.RELEASE</spring-boot.version>
</properties>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>${spring-boot.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

加上mongoDB的starter配置

代码语言:javascript复制
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

加上PageHelper

代码语言:javascript复制
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.10</version>
</dependency>

PageHelper分页

代码语言:javascript复制
package com.example.mongodb.common.page;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.Data;

import java.util.List;

@Data
public class PageBean {

    // 当前页
    private Integer pageIndex = 1;
    // 一页的条数
    private Integer pageRowNum = 10;

    @JsonIgnore
    private Page pages;

    public void initPage() {
        this.pages = PageHelper.startPage(pageIndex , pageRowNum);
    }

    public PageDataBean loadData(List dataList) {
        return new PageDataBean(dataList , pages.getTotal() , pageIndex , pageRowNum);
    }
}

返回给前端的数据

代码语言:javascript复制
package com.example.mongodb.common.page;


import lombok.Data;

import java.util.ArrayList;
import java.util.List;

@Data
public class PageDataBean<T> {

    private List<T> dataList = new ArrayList<>();

    private PageObject pageObj = new PageObject();

    public PageDataBean(List<T> dataList , Long totalRow , Integer pageIndex , Integer pageRowNum) {
        this.dataList = dataList;
        pageObj.setPageIndex(pageIndex);
        pageObj.setPageRowNum(pageRowNum);
        pageObj.setTotalRow(totalRow);
        pageObj.setTotalPage(totalRow / pageRowNum   (totalRow % pageRowNum == 0 ? 0 : 1));
    }

}

分页对象数据、返回当前页、每页数量、总页数、总数量

代码语言:javascript复制
package com.example.mongodb.common.page;

import lombok.Data;

@Data
public class PageObject {
    // 当前页
    private long pageIndex;
    // 每页数量
    private long pageRowNum;
    // 总页数
    private long totalPage;
    // 总数量
    private long totalRow;

}

用户数据例子

新建一个类,@Document指定文档名称

代码语言:javascript复制
package com.example.mongodb.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.SuperBuilder;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.MongoId;

import java.io.Serializable;

@Data
@SuperBuilder(toBuilder = true)
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Document(collection = "user")
public class User implements Serializable {
    @MongoId
    private Long id;
    private String name;
    private Integer age;
    private String email;

}

API接口

代码语言:javascript复制
import com.example.mongodb.common.page.PageBean;
import com.example.mongodb.common.page.PageDataBean;
import com.example.mongodb.model.User;
import java.util.List;

public interface IUserService {

    PageDataBean<List<User>> pageList(PageBean pageBean , User queryParam);

}

调用分页例子

代码语言:javascript复制
package com.example.mongodb.service.impl;


import cn.hutool.core.util.StrUtil;
import com.example.mongodb.common.page.PageBean;
import com.example.mongodb.common.page.PageDataBean;
import com.example.mongodb.model.User;
import com.example.mongodb.repository.UserRepository;
import com.example.mongodb.service.IUserService;
import com.github.pagehelper.Page;
import com.mongodb.BasicDBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private MongoTemplate mongoTemplate;
    
    @Override
    public PageDataBean<List<User>> pageList(PageBean pageBean, User queryParam) {
        pageBean.initPage();
        MongoCollection<Document> collection = mongoTemplate.getCollection("user");
        Page page = new Page();
        page.setTotal(collection.countDocuments());
        pageBean.setPages(page);

        Document params = new Document();
        if (StrUtil.isNotBlank(queryParam.getName())) {
            params.append("name", queryParam.getName());
        }
        Bson orderBy = new BasicDBObject("_id" , -1);
        FindIterable<Document> iterable = collection.find(params).sort(orderBy).skip((pageBean.getPageIndex() - 1) * pageBean.getPageRowNum()).limit(pageBean.getPageRowNum());
        MongoCursor<Document> cursor = iterable.iterator();
        List<Document> result = new ArrayList<>();
        while (cursor.hasNext()) {
            Document doc = cursor.next();
            result.add(doc);
        }

        return pageBean.loadData(result);
    }

}

分页接口

代码语言:javascript复制
import cn.hutool.core.bean.BeanUtil;
import com.example.mongodb.common.page.PageBean;
import com.example.mongodb.common.page.PageDataBean;
import com.example.mongodb.common.rest.ResultBean;
import com.example.mongodb.model.User;
import com.example.mongodb.model.dto.UserDto;
import com.example.mongodb.model.vo.UserVo;
import com.example.mongodb.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping(value = "/api")
public class UserController {

    @Autowired
    private IUserService userService;

    @GetMapping(value = "/user/pageList")
    public ResultBean<PageDataBean<List<User>>> pageList(PageBean pageBean , User param) {
        PageDataBean<List<User>> pageDataBean = userService.pageList(pageBean, param);
        return ResultBean.ok(pageDataBean);
    }


}

定义一个ResultBean,返回给前端

代码语言:javascript复制
package com.example.mongodb.common.rest;

import lombok.Data;
import org.springframework.http.HttpStatus;

@Data
public class ResultBean<T> {

	/**
	 * 状态
	 * */
	private int status;
	/**
	 * 描述
	 * */
	private String desc;
	/**
	 * 数据返回
	 * */
	private T data;

	public ResultBean(int status, String desc, T data) {
		this.status = status;
		this.desc = desc;
		this.data = data;
	}

	public ResultBean(T data) {
		this.status = HttpStatus.OK.value();
		this.desc = "处理成功";
		this.data = data;
	}

	public static <T> ResultBean<T> ok(T data) {
		return new ResultBean(data);
	}

	public static <T> ResultBean<T> ok() {
		return new ResultBean(null);
	}

	public static <T> ResultBean<T> badRequest(String desc,T data) {
		return new ResultBean(HttpStatus.BAD_REQUEST.value(), desc, data);
	}

	public static <T> ResultBean<T> badRequest(String desc) {
		return new ResultBean(HttpStatus.BAD_REQUEST.value(), desc, null);
	}

	public static <T> ResultBean serverError(String desc, T data){
		return new ResultBean(HttpStatus.INTERNAL_SERVER_ERROR.value(),"服务器内部异常:" desc,data);
	}

	public static <T> ResultBean serverError(String desc){
		return new ResultBean(HttpStatus.INTERNAL_SERVER_ERROR.value(),"服务器内部异常:" desc,null);
	}

}

0 人点赞