CommonService.java 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package com.zswl.dataservice.service.base;
  2. import com.mongodb.client.result.UpdateResult;
  3. import com.zswl.dataservice.utils.CommonUtil;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.apache.commons.lang3.StringUtils;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.data.mongodb.core.MongoTemplate;
  8. import org.springframework.data.mongodb.core.query.Criteria;
  9. import org.springframework.data.mongodb.core.query.Query;
  10. import org.springframework.data.mongodb.core.query.Update;
  11. import org.springframework.stereotype.Service;
  12. import java.util.Map;
  13. /**
  14. * @author TRX
  15. * @date 2024/5/31
  16. */
  17. @Slf4j
  18. @Service
  19. public class CommonService {
  20. @Autowired
  21. private MongoTemplate mongoTemplate;
  22. /**
  23. * 编辑数据
  24. *
  25. * @param standardData
  26. * @param collectionName
  27. * @return
  28. */
  29. public Object updateData(Map<String, Object> standardData, String collectionName) {
  30. collectionName = CommonUtil.getCollectionName(collectionName);
  31. Object id = standardData.get("id");
  32. if (id != null) {
  33. Query query = new Query(Criteria.where("_id").is(id));
  34. Update update = new Update();
  35. standardData.forEach((key, value) -> {
  36. if (!"id".equals(key)) {
  37. update.set(key, value);
  38. }
  39. });
  40. UpdateResult updateResult = mongoTemplate.updateMulti(query, update, collectionName);
  41. return updateResult.getUpsertedId();
  42. }
  43. return null;
  44. }
  45. public Object updateData(Map<String, Object> where, Map<String, Object> standardData, String collectionName) {
  46. collectionName = CommonUtil.getCollectionName(collectionName);
  47. Criteria criteria = new Criteria();
  48. if (where != null) {
  49. where.forEach((key, value) -> {
  50. criteria.and(key).is(value);
  51. });
  52. }
  53. Query query = new Query(criteria);
  54. Update update = new Update();
  55. standardData.forEach((key, value) -> {
  56. if (!"id".equals(key)) {
  57. update.set(key, value);
  58. }
  59. });
  60. UpdateResult updateResult = mongoTemplate.updateMulti(query, update, collectionName);
  61. return updateResult.getUpsertedId();
  62. }
  63. }