java?MongoDB實(shí)現(xiàn)列表分頁查詢的示例代碼
查詢工具類
package com.bx.utils;
import com.google.common.collect.Lists;
import com.java.framework.model.WebViewModel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;
import static org.springframework.data.mongodb.core.query.Criteria.where;
/**
* @author: buwt
* @date: 2023/02/01
* @time: 12:45
*/
public class MongodbCriteriaUtils {
public static void setQuery(Query query, WebViewModel model) {
WebViewModel.Relation relation = model.getRelationsCondition();
if (relation == null) {
List<WebViewModel.Condition> conditions = model.getCondition();
if (conditions == null || conditions.isEmpty()) {
return;
}
relation = new WebViewModel.Relation();
relation.setRelationType("AND");
relation.setConditions(conditions);
}
List<Criteria> criteriaList = getCriteria(relation);
if (criteriaList.isEmpty()) {
return;
}
query.addCriteria(operator(relation.getRelationType(), criteriaList));
}
public static Pageable pageable(WebViewModel viewModel) {
WebViewModel.Page page = viewModel.getPage();
int currPage = page.getCurrPage();
int pageSize = page.getPageSize();
if (pageSize < 1) {
pageSize = 10;
}
List<WebViewModel.Order> orders = viewModel.getOrder();
if (orders != null && orders.size() > 0) {
List<Sort.Order> orderList = Lists.newArrayList();
for (WebViewModel.Order order : orders) {
try {
if (StringUtils.isBlank(order.getColName())) {
continue;
}
Sort.Order ord;
if (StringUtils.isBlank(order.getOrderType())) {
ord = new Sort.Order(Sort.Direction.ASC, order.getColName());
} else {
ord = new Sort.Order(Sort.Direction.fromString(order.getOrderType()), order.getColName());
}
orderList.add(ord);
} catch (Exception e) {
e.printStackTrace();
}
}
if (!orders.isEmpty()) {
Sort sort = new Sort(orderList);
return new PageRequest(Math.max(currPage - 1, 0), pageSize, sort);
}
}
return new PageRequest(Math.max(currPage - 1, 0), pageSize);
}
private static List<Criteria> getCriteria(WebViewModel.Relation relation) {
List<Criteria> criteriaList = new ArrayList<>();
List<WebViewModel.Condition> conditions = relation.getConditions();
List<WebViewModel.Relation> relations = relation.getRelations();
if (isNotEmpty(conditions)) {
for (WebViewModel.Condition condition : conditions) {
if (StringUtils.isBlank(condition.getColName())) {
continue;
}
Criteria criteria = getCriteria(condition.getColName(), condition.getRuleType(), condition.getValue());
if (criteria == null) {
continue;
}
criteriaList.add(criteria);
}
}
if (isNotEmpty(relations)) {
for (WebViewModel.Relation relation1 : relations) {
List<Criteria> critters = getCriteria(relation1);
if (isNotEmpty(critters)) {
Criteria criteria = operator(relation1.getRelationType(), critters);
criteriaList.add(criteria);
}
}
}
return criteriaList;
}
private static boolean isEmpty(Collection<?> collection) {
return collection == null || collection.isEmpty();
}
private static boolean isNotEmpty(Collection<?> collection) {
return !isEmpty(collection);
}
private static Criteria getCriteria(String colName, String ruleType, Object value) {
if (StringUtils.isBlank(ruleType)) {
ruleType = "EQ";
}
switch (ruleType.toUpperCase()) {
case "NE":
return where(colName).ne(value);
case "LIKE":
return where(colName).regex(Pattern.compile("^.*" + value + ".*$"));
case "IN": {
if (value == null || StringUtils.isBlank(value.toString())) {
return null;
}
ArrayList<String> arrayList = Lists.newArrayList(value.toString().split(","));
return where(colName).in(arrayList);
}
case "NIN": {
if (value == null || StringUtils.isBlank(value.toString())) {
return null;
}
ArrayList<String> arrayList = Lists.newArrayList(value.toString().split(","));
return where(colName).nin(arrayList);
}
case "GE":
return where(colName).gte(value);
case "LE":
return where(colName).lte(value);
case "GT":
return where(colName).gt(value);
case "LT":
return where(colName).lt(value);
case "EQ":
default:
return where(colName).is(value);
}
}
private static Criteria operator(String ruleType, List<Criteria> criteriaList) {
Criteria criteria = new Criteria();
switch (ruleType.toUpperCase()) {
case "OR":
criteria.orOperator(criteriaList.toArray(new Criteria[0]));
break;
case "AND":
default:
criteria.andOperator(criteriaList.toArray(new Criteria[0]));
break;
}
return criteria;
}
}WebViewModel 對(duì)象(列表接口請(qǐng)求對(duì)象)
package com.java.framework.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
@JsonIgnoreProperties(ignoreUnknown = true)
@ApiModel(value = "查詢數(shù)據(jù)請(qǐng)求對(duì)象", description = "前端的數(shù)據(jù)查詢接口請(qǐng)求數(shù)據(jù)封裝到這個(gè)對(duì)象")
public class WebViewModel implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
// 查詢條件
private List<Condition> condition;
//關(guān)系條件
private Relation relationsCondition;
//組
// private List<Map<String,Object>> group;
// 排序
private List<Order> order;
// 分頁
private Page page;
public List<Condition> getCondition() {
return condition;
}
public void setCondition(List<Condition> condition) {
this.condition = condition;
}
public List<Order> getOrder() {
return order;
}
public void setOrder(List<Order> order) {
this.order = order;
}
public Page getPage() {
return page;
}
public void setPage(Page page) {
this.page = page;
}
public Relation getRelationsCondition() {
return relationsCondition;
}
public void setRelationsCondition(Relation relationsCondition) {
this.relationsCondition = relationsCondition;
}
// 條件
// @ApiModel(value = "查詢條件", description = "查詢條件組裝對(duì)象")
public static class Condition implements Serializable{
@ApiModelProperty(value = "屬性名(property)")
private String colName;
@ApiModelProperty(value = "匹配規(guī)則", allowableValues = "EQ, NE, LIKE, GT, LT, GE, LE, IN, NIN")
private String ruleType;
@ApiModelProperty(value = "屬性值")
private Object value;
public Condition() {
// TODO Auto-generated constructor stub
}
public String getColName() {
return colName;
}
public void setColName(String colName) {
this.colName = colName;
}
public String getRuleType() {
return ruleType;
}
public void setRuleType(String ruleType) {
this.ruleType = ruleType;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
@Override
public String toString() {
return "Condition {colName=" + colName + ", ruleType=" + ruleType + ", value=" + value + "}";
}
}
public static class Relation implements Serializable {
@ApiModelProperty(value = "條件關(guān)系符(默認(rèn)AND)", allowableValues = "AND,OR")
private String relationType = "AND";
private List<Condition> conditions = new ArrayList<>();
private List<Relation> relations = new ArrayList<>();
public Relation(){}
public String getRelationType() {
return relationType;
}
public void setRelationType(String relationType) {
this.relationType = relationType;
}
public List<Condition> getConditions() {
return conditions;
}
public void setConditions(List<Condition> conditions) {
this.conditions = conditions;
}
public void addCondition(Condition condition) {
this.conditions.add(condition);
}
public void removeCondition(Condition condition) {
this.conditions.remove(condition);
}
public List<Relation> getRelations() {
return relations;
}
public void setRelations(List<Relation> relations) {
this.relations = relations;
}
@Override
public String toString() {
return "Relation{" +
"relationType='" + relationType + '\'' +
", conditions=" + conditions +
", relations=" + relations +
'}';
}
}
// @ApiModel(value = "排序?qū)ο?, description = "排序方式組裝對(duì)象")
public static class Order implements Serializable {
@ApiModelProperty(value = "屬性名(property)")
private String colName;
@ApiModelProperty(value = "排序類型", allowableValues = "asc,desc")
private String orderType;
public String getColName() {
return colName;
}
public void setColName(String colName) {
this.colName = colName;
}
public String getOrderType() {
return orderType;
}
public void setOrderType(String orderType) {
this.orderType = orderType;
}
@Override
public String toString() {
return "Order [colName=" + colName + ", orderType=" + orderType + "]";
}
}
@ApiModel(value = "分頁對(duì)象", description = "分頁數(shù)據(jù)組裝對(duì)象")
public static class Page implements Serializable {
@ApiModelProperty(value = "當(dāng)前頁碼", dataType = "int", required = true)
private int currPage;
@ApiModelProperty(value = "每頁條數(shù)", dataType = "int", required = true)
private int pageSize;
public int getCurrPage() {
return currPage;
}
public void setCurrPage(int currPage) {
this.currPage = currPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
@Override
public String toString() {
return "Page [currPage=" + currPage + ", pageSize=" + pageSize + "]";
}
}
}代碼示例
@PostMapping("taskDoListTwo")
@ApiOperation("我的已辦")
public DataModel<ProcessHandleHistory> taskDoListTwo(@RequestBody WebViewModel model) throws Exception {
Pageable pageable = MongodbCriteriaUtils.pageable(model);
Query query = new Query();
MongodbCriteriaUtils.setQuery(query, model);
List<ProcessHandleHistory> handleHistories =
mongoTemplate.find(query.with(pageable), ProcessHandleHistory.class, "process_handle_history");
long count = mongoTemplate.count(query, ProcessHandleHistory.class, "process_handle_history");
return SupplierHelper.create(DataModel.Builder<ProcessHandleHistory>::new)
.setDatas(handleHistories)
.setTotal(count)
.setPageSize(pageable.getPageSize())
.setCurrPage(pageable.getPageNumber()+1)
.setTotalPages((int) (count / pageable.getPageSize()))
.build();
}查詢示例
{
"page": {
"currPage": 0,
"pageSize": 10
},
"condition": [
{
"colName": "owner",
"ruleType": "EQ",
"value": "5d5a3cebcfb7e91344537723"
},
{
"colName": "commentType",
"ruleType": "NE",
"value": "發(fā)起申請(qǐng)"
},
{
"colName": "applyUser.bussTitle",
"ruleType": "LIKE",
"value": "測(cè)試"
}
],
"order": [
{
"colName": "startTime",
"orderType": "desc"
}
]
}響應(yīng)示例
{
"flag": true,
"shortMessage": null,
"message": null,
"condition": null,
"datas": [
{
"applyUser": {
"applyUser": "吳婷婷",
"bussTitle": "測(cè)試27",
"bussId": "60adece23bc08a6180fd966c"
},
"owner": "5d5a3cebcfb7e91344537723"
},
{
"applyUser": {
"applyUser": "administ",
"bussTitle": "新流程測(cè)試",
"bussId": "5efef4fbe42b5a09cd7f3205"
}
"owner": "5d5a3cebcfb7e91344537723"
}
],
"data": null,
"page": {
"currPage": 1,
"pageSize": 10,
"total": 53,
"totalPages": 5
}
}到此這篇關(guān)于java MongoDB實(shí)現(xiàn)列表分頁查詢的示例代碼的文章就介紹到這了,更多相關(guān)java MongoDB 列表分頁查詢內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java中棧和隊(duì)列的實(shí)現(xiàn)和API的用法(詳解)
下面小編就為大家?guī)硪黄猨ava中棧和隊(duì)列的實(shí)現(xiàn)和API的用法(詳解)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-05-05
從零開始學(xué)Java之關(guān)系運(yùn)算符
今天帶大家復(fù)習(xí)Java關(guān)系運(yùn)算符,文中對(duì)Java運(yùn)算符相關(guān)知識(shí)作了詳細(xì)總結(jié),對(duì)正在學(xué)習(xí)java基礎(chǔ)的小伙伴們很有幫助,需要的朋友可以參考下2021-08-08
maven assembly打包生成Java應(yīng)用啟動(dòng)腳本bat和sh的方法
springboot應(yīng)用通過maven插件appassembler-maven-plugi生成啟動(dòng)腳本bat和sh,這篇文章主要介紹了maven assembly打包生成Java應(yīng)用啟動(dòng)腳本bat和sh,需要的朋友可以參考下2022-11-11
淺談Java實(shí)現(xiàn)面向?qū)ο缶幊蘪ava oop
這篇文章主要介紹了淺談Java實(shí)現(xiàn)面向?qū)ο缶幊蘪ava oop,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07
Java通過反射,如何動(dòng)態(tài)修改注解的某個(gè)屬性值
這篇文章主要介紹了Java通過反射,動(dòng)態(tài)修改注解的某個(gè)屬性值操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07
Spring5中SpringWebContext方法過時(shí)的解決方案
這篇文章主要介紹了Spring5中SpringWebContext方法過時(shí)的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01
解讀controller層,service層,mapper層,entity層的作用與聯(lián)系
這篇文章主要介紹了關(guān)于controller層,service層,mapper層,entity層的作用與聯(lián)系,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11

