当前位置:   article > 正文

java MongoDB 列表分页查询_java mongodb分页查询

java mongodb分页查询

Java MongoDB分页查询

查询工具类

  1. package com.bx.utils;
  2. import com.google.common.collect.Lists;
  3. import com.java.framework.model.WebViewModel;
  4. import org.apache.commons.lang3.StringUtils;
  5. import org.springframework.data.domain.PageRequest;
  6. import org.springframework.data.domain.Pageable;
  7. import org.springframework.data.domain.Sort;
  8. import org.springframework.data.mongodb.core.query.Criteria;
  9. import org.springframework.data.mongodb.core.query.Query;
  10. import java.util.ArrayList;
  11. import java.util.Collection;
  12. import java.util.List;
  13. import java.util.regex.Pattern;
  14. import static org.springframework.data.mongodb.core.query.Criteria.where;
  15. /**
  16. * @author: buwt
  17. * @date: 2023/02/01
  18. * @time: 12:45
  19. */
  20. public class MongodbCriteriaUtils {
  21. public static void setQuery(Query query, WebViewModel model) {
  22. WebViewModel.Relation relation = model.getRelationsCondition();
  23. if (relation == null) {
  24. List<WebViewModel.Condition> conditions = model.getCondition();
  25. if (conditions == null || conditions.isEmpty()) {
  26. return;
  27. }
  28. relation = new WebViewModel.Relation();
  29. relation.setRelationType("AND");
  30. relation.setConditions(conditions);
  31. }
  32. List<Criteria> criteriaList = getCriteria(relation);
  33. if (criteriaList.isEmpty()) {
  34. return;
  35. }
  36. query.addCriteria(operator(relation.getRelationType(), criteriaList));
  37. }
  38. public static Pageable pageable(WebViewModel viewModel) {
  39. WebViewModel.Page page = viewModel.getPage();
  40. int currPage = page.getCurrPage();
  41. int pageSize = page.getPageSize();
  42. if (pageSize < 1) {
  43. pageSize = 10;
  44. }
  45. List<WebViewModel.Order> orders = viewModel.getOrder();
  46. if (orders != null && orders.size() > 0) {
  47. List<Sort.Order> orderList = Lists.newArrayList();
  48. for (WebViewModel.Order order : orders) {
  49. try {
  50. if (StringUtils.isBlank(order.getColName())) {
  51. continue;
  52. }
  53. Sort.Order ord;
  54. if (StringUtils.isBlank(order.getOrderType())) {
  55. ord = new Sort.Order(Sort.Direction.ASC, order.getColName());
  56. } else {
  57. ord = new Sort.Order(Sort.Direction.fromString(order.getOrderType()), order.getColName());
  58. }
  59. orderList.add(ord);
  60. } catch (Exception e) {
  61. e.printStackTrace();
  62. }
  63. }
  64. if (!orders.isEmpty()) {
  65. Sort sort = new Sort(orderList);
  66. return new PageRequest(Math.max(currPage - 1, 0), pageSize, sort);
  67. }
  68. }
  69. return new PageRequest(Math.max(currPage - 1, 0), pageSize);
  70. }
  71. private static List<Criteria> getCriteria(WebViewModel.Relation relation) {
  72. List<Criteria> criteriaList = new ArrayList<>();
  73. List<WebViewModel.Condition> conditions = relation.getConditions();
  74. List<WebViewModel.Relation> relations = relation.getRelations();
  75. if (isNotEmpty(conditions)) {
  76. for (WebViewModel.Condition condition : conditions) {
  77. if (StringUtils.isBlank(condition.getColName())) {
  78. continue;
  79. }
  80. Criteria criteria = getCriteria(condition.getColName(), condition.getRuleType(), condition.getValue());
  81. if (criteria == null) {
  82. continue;
  83. }
  84. criteriaList.add(criteria);
  85. }
  86. }
  87. if (isNotEmpty(relations)) {
  88. for (WebViewModel.Relation relation1 : relations) {
  89. List<Criteria> critters = getCriteria(relation1);
  90. if (isNotEmpty(critters)) {
  91. Criteria criteria = operator(relation1.getRelationType(), critters);
  92. criteriaList.add(criteria);
  93. }
  94. }
  95. }
  96. return criteriaList;
  97. }
  98. private static boolean isEmpty(Collection<?> collection) {
  99. return collection == null || collection.isEmpty();
  100. }
  101. private static boolean isNotEmpty(Collection<?> collection) {
  102. return !isEmpty(collection);
  103. }
  104. private static Criteria getCriteria(String colName, String ruleType, Object value) {
  105. if (StringUtils.isBlank(ruleType)) {
  106. ruleType = "EQ";
  107. }
  108. switch (ruleType.toUpperCase()) {
  109. case "NE":
  110. return where(colName).ne(value);
  111. case "LIKE":
  112. return where(colName).regex(Pattern.compile("^.*" + value + ".*$"));
  113. case "IN": {
  114. if (value == null || StringUtils.isBlank(value.toString())) {
  115. return null;
  116. }
  117. ArrayList<String> arrayList = Lists.newArrayList(value.toString().split(","));
  118. return where(colName).in(arrayList);
  119. }
  120. case "NIN": {
  121. if (value == null || StringUtils.isBlank(value.toString())) {
  122. return null;
  123. }
  124. ArrayList<String> arrayList = Lists.newArrayList(value.toString().split(","));
  125. return where(colName).nin(arrayList);
  126. }
  127. case "GE":
  128. return where(colName).gte(value);
  129. case "LE":
  130. return where(colName).lte(value);
  131. case "GT":
  132. return where(colName).gt(value);
  133. case "LT":
  134. return where(colName).lt(value);
  135. case "EQ":
  136. default:
  137. return where(colName).is(value);
  138. }
  139. }
  140. private static Criteria operator(String ruleType, List<Criteria> criteriaList) {
  141. Criteria criteria = new Criteria();
  142. switch (ruleType.toUpperCase()) {
  143. case "OR":
  144. criteria.orOperator(criteriaList.toArray(new Criteria[0]));
  145. break;
  146. case "AND":
  147. default:
  148. criteria.andOperator(criteriaList.toArray(new Criteria[0]));
  149. break;
  150. }
  151. return criteria;
  152. }
  153. }

WebViewModel 对象(列表接口请求对象)

  1. package com.java.framework.model;
  2. import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
  3. import com.fasterxml.jackson.core.JsonProcessingException;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import io.swagger.annotations.ApiModel;
  6. import io.swagger.annotations.ApiModelProperty;
  7. import java.io.Serializable;
  8. import java.io.StringWriter;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. @JsonIgnoreProperties(ignoreUnknown = true)
  12. @ApiModel(value = "查询数据请求对象", description = "前端的数据查询接口请求数据封装到这个对象")
  13. public class WebViewModel implements Serializable {
  14. /**
  15. *
  16. */
  17. private static final long serialVersionUID = 1L;
  18. // 查询条件
  19. private List<Condition> condition;
  20. //关系条件
  21. private Relation relationsCondition;
  22. //组
  23. // private List<Map<String,Object>> group;
  24. // 排序
  25. private List<Order> order;
  26. // 分页
  27. private Page page;
  28. public List<Condition> getCondition() {
  29. return condition;
  30. }
  31. public void setCondition(List<Condition> condition) {
  32. this.condition = condition;
  33. }
  34. public List<Order> getOrder() {
  35. return order;
  36. }
  37. public void setOrder(List<Order> order) {
  38. this.order = order;
  39. }
  40. public Page getPage() {
  41. return page;
  42. }
  43. public void setPage(Page page) {
  44. this.page = page;
  45. }
  46. public Relation getRelationsCondition() {
  47. return relationsCondition;
  48. }
  49. public void setRelationsCondition(Relation relationsCondition) {
  50. this.relationsCondition = relationsCondition;
  51. }
  52. // 条件
  53. // @ApiModel(value = "查询条件", description = "查询条件组装对象")
  54. public static class Condition implements Serializable{
  55. @ApiModelProperty(value = "属性名(property)")
  56. private String colName;
  57. @ApiModelProperty(value = "匹配规则", allowableValues = "EQ, NE, LIKE, GT, LT, GE, LE, IN, NIN")
  58. private String ruleType;
  59. @ApiModelProperty(value = "属性值")
  60. private Object value;
  61. public Condition() {
  62. // TODO Auto-generated constructor stub
  63. }
  64. public String getColName() {
  65. return colName;
  66. }
  67. public void setColName(String colName) {
  68. this.colName = colName;
  69. }
  70. public String getRuleType() {
  71. return ruleType;
  72. }
  73. public void setRuleType(String ruleType) {
  74. this.ruleType = ruleType;
  75. }
  76. public Object getValue() {
  77. return value;
  78. }
  79. public void setValue(Object value) {
  80. this.value = value;
  81. }
  82. @Override
  83. public String toString() {
  84. return "Condition {colName=" + colName + ", ruleType=" + ruleType + ", value=" + value + "}";
  85. }
  86. }
  87. public static class Relation implements Serializable {
  88. @ApiModelProperty(value = "条件关系符(默认AND)", allowableValues = "AND,OR")
  89. private String relationType = "AND";
  90. private List<Condition> conditions = new ArrayList<>();
  91. private List<Relation> relations = new ArrayList<>();
  92. public Relation(){}
  93. public String getRelationType() {
  94. return relationType;
  95. }
  96. public void setRelationType(String relationType) {
  97. this.relationType = relationType;
  98. }
  99. public List<Condition> getConditions() {
  100. return conditions;
  101. }
  102. public void setConditions(List<Condition> conditions) {
  103. this.conditions = conditions;
  104. }
  105. public void addCondition(Condition condition) {
  106. this.conditions.add(condition);
  107. }
  108. public void removeCondition(Condition condition) {
  109. this.conditions.remove(condition);
  110. }
  111. public List<Relation> getRelations() {
  112. return relations;
  113. }
  114. public void setRelations(List<Relation> relations) {
  115. this.relations = relations;
  116. }
  117. @Override
  118. public String toString() {
  119. return "Relation{" +
  120. "relationType='" + relationType + '\'' +
  121. ", conditions=" + conditions +
  122. ", relations=" + relations +
  123. '}';
  124. }
  125. }
  126. // @ApiModel(value = "排序对象", description = "排序方式组装对象")
  127. public static class Order implements Serializable {
  128. @ApiModelProperty(value = "属性名(property)")
  129. private String colName;
  130. @ApiModelProperty(value = "排序类型", allowableValues = "asc,desc")
  131. private String orderType;
  132. public String getColName() {
  133. return colName;
  134. }
  135. public void setColName(String colName) {
  136. this.colName = colName;
  137. }
  138. public String getOrderType() {
  139. return orderType;
  140. }
  141. public void setOrderType(String orderType) {
  142. this.orderType = orderType;
  143. }
  144. @Override
  145. public String toString() {
  146. return "Order [colName=" + colName + ", orderType=" + orderType + "]";
  147. }
  148. }
  149. @ApiModel(value = "分页对象", description = "分页数据组装对象")
  150. public static class Page implements Serializable {
  151. @ApiModelProperty(value = "当前页码", dataType = "int", required = true)
  152. private int currPage;
  153. @ApiModelProperty(value = "每页条数", dataType = "int", required = true)
  154. private int pageSize;
  155. public int getCurrPage() {
  156. return currPage;
  157. }
  158. public void setCurrPage(int currPage) {
  159. this.currPage = currPage;
  160. }
  161. public int getPageSize() {
  162. return pageSize;
  163. }
  164. public void setPageSize(int pageSize) {
  165. this.pageSize = pageSize;
  166. }
  167. @Override
  168. public String toString() {
  169. return "Page [currPage=" + currPage + ", pageSize=" + pageSize + "]";
  170. }
  171. }
  172. }

代码示例

  1. @PostMapping("taskDoListTwo")
  2. @ApiOperation("我的已办")
  3. public DataModel<ProcessHandleHistory> taskDoListTwo(@RequestBody WebViewModel model) throws Exception {
  4. Pageable pageable = MongodbCriteriaUtils.pageable(model);
  5. Query query = new Query();
  6. MongodbCriteriaUtils.setQuery(query, model);
  7. List<ProcessHandleHistory> handleHistories =
  8. mongoTemplate.find(query.with(pageable), ProcessHandleHistory.class, "process_handle_history");
  9. long count = mongoTemplate.count(query, ProcessHandleHistory.class, "process_handle_history");
  10. return SupplierHelper.create(DataModel.Builder<ProcessHandleHistory>::new)
  11. .setDatas(handleHistories)
  12. .setTotal(count)
  13. .setPageSize(pageable.getPageSize())
  14. .setCurrPage(pageable.getPageNumber()+1)
  15. .setTotalPages((int) (count / pageable.getPageSize()))
  16. .build();
  17. }

查询示例

  1. {
  2. "page": {
  3. "currPage": 0,
  4. "pageSize": 10
  5. },
  6. "condition": [
  7. {
  8. "colName": "owner",
  9. "ruleType": "EQ",
  10. "value": "5d5a3cebcfb7e91344537723"
  11. },
  12. {
  13. "colName": "commentType",
  14. "ruleType": "NE",
  15. "value": "发起申请"
  16. },
  17. {
  18. "colName": "applyUser.bussTitle",
  19. "ruleType": "LIKE",
  20. "value": "测试"
  21. }
  22. ],
  23. "order": [
  24. {
  25. "colName": "startTime",
  26. "orderType": "desc"
  27. }
  28. ]
  29. }

响应示例

  1. {
  2. "flag": true,
  3. "shortMessage": null,
  4. "message": null,
  5. "condition": null,
  6. "datas": [
  7. {
  8. "applyUser": {
  9. "applyUser": "吴婷婷",
  10. "bussTitle": "测试27",
  11. "bussId": "60adece23bc08a6180fd966c"
  12. },
  13. "owner": "5d5a3cebcfb7e91344537723"
  14. },
  15. {
  16. "applyUser": {
  17. "applyUser": "administ",
  18. "bussTitle": "新流程测试",
  19. "bussId": "5efef4fbe42b5a09cd7f3205"
  20. }
  21. "owner": "5d5a3cebcfb7e91344537723"
  22. }
  23. ],
  24. "data": null,
  25. "page": {
  26. "currPage": 1,
  27. "pageSize": 10,
  28. "total": 53,
  29. "totalPages": 5
  30. }
  31. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/56053
推荐阅读
相关标签
  

闽ICP备14008679号