|
@@ -0,0 +1,65 @@
|
|
|
+package com.ruixuan.common.utils.mongodb;
|
|
|
+
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.springframework.beans.factory.annotation.Autowired;
|
|
|
+import org.springframework.data.mongodb.core.MongoTemplate;
|
|
|
+import org.springframework.data.mongodb.core.query.Criteria;
|
|
|
+import org.springframework.data.mongodb.core.query.Query;
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
+
|
|
|
+import java.util.ArrayList;
|
|
|
+import java.util.List;
|
|
|
+
|
|
|
+/**
|
|
|
+ * MongoDB 工具类
|
|
|
+ */
|
|
|
+@Slf4j
|
|
|
+@Component
|
|
|
+public class MongoDBDemo {
|
|
|
+
|
|
|
+ @Autowired
|
|
|
+ private MongoTemplate mongoTemplate;
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 新增:
|
|
|
+ * 说一下insert和save的区别:
|
|
|
+ * 1)插入重复数据时:
|
|
|
+ * insert: 若新增数据的主键已经存在,则会抛 DuplicateKeyException 异常提示主键重复,不保存当前数据。
|
|
|
+ * save: 若新增数据的主键已经存在,则会对当前已经存在的数据进行修改操作。
|
|
|
+ * 2)批操作时:
|
|
|
+ * insert: 可以一次性插入一整个列表,不用进行遍历操作,效率相对较高。
|
|
|
+ * save: 需要遍历列表,进行一个个的插入,效率相对较低。
|
|
|
+ */
|
|
|
+ public void save() {
|
|
|
+ PeopleDemo people = new PeopleDemo("zhangsan", "zhangsan", "张三", "13889625648");
|
|
|
+ mongoTemplate.save(people);
|
|
|
+ log.info("save ok");
|
|
|
+ }
|
|
|
+
|
|
|
+ public void saveAll() {
|
|
|
+ List<PeopleDemo> list = new ArrayList();
|
|
|
+ PeopleDemo people = new PeopleDemo("zhangsan", "zhangsan2", "张三", "13312345678");
|
|
|
+ PeopleDemo people2 = new PeopleDemo("lisi", "lisi", "李四", "15512345678");
|
|
|
+ list.add(people);
|
|
|
+ list.add(people2);
|
|
|
+// mongoTemplate.insertAll(list);
|
|
|
+ for (PeopleDemo demo : list) {
|
|
|
+ mongoTemplate.save(demo);
|
|
|
+ }
|
|
|
+ log.info("saveAll ok");
|
|
|
+ }
|
|
|
+
|
|
|
+ public void find() {
|
|
|
+ new PeopleDemo();
|
|
|
+ Criteria criteria = new Criteria();
|
|
|
+ criteria = Criteria.where("userId").is("zhangsan");
|
|
|
+ Query query = new Query(criteria);
|
|
|
+
|
|
|
+ List<PeopleDemo> list = mongoTemplate.find(query, PeopleDemo.class);
|
|
|
+ List<PeopleDemo> all = mongoTemplate.findAll(PeopleDemo.class);
|
|
|
+ System.out.println("条件筛选结果:" + list);
|
|
|
+ System.out.println("----All结果:" + all);
|
|
|
+ log.info("find ok");
|
|
|
+ }
|
|
|
+
|
|
|
+}
|