RecordsServiceImpl实现代码如下:
package com.example.demo123456.ServciceImpl;
import com.example.demo123456.dao.RecordsDao; import com.example.demo123456.model.Records; import org.bson.Document; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.BulkOperations; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.stereotype.Service;
import java.util.ArrayList; import java.util.List; import java.util.Map;
public class RecordsServiceImpl implements RecordsDao {
@Autowired
private MongoTemplate mongoTemplate;
[@Override](https://my.oschina.net/u/1162528)
public void insertAllMongo(List<Map<String, Object>> batchList) throws Exception {
BulkOperations ops = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, "x67");
List<Document> documentList = new ArrayList<>();
//获取map,然后以map方式存入
for (Map<String, Object> listmap : batchList) {
Document doc = new Document();
doc.putAll(listmap);
documentList.add(doc);
}
System.out.println("看看list里面存放的啥" + documentList);
try {
ops.insert(documentList);
ops.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
}
接口RecordsDao实现代码如下: package com.example.demo123456.dao;
import java.util.List; import java.util.Map;
public interface RecordsDao { void insertAllMongo(List<Map<String, Object>> batchList)throws Exception; }
其中测试代码如下: package com.example.demo123456;
import com.example.demo123456.dao.RecordsDao; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList; import java.util.HashMap; import java.util.Map;
@RunWith(SpringRunner.class) @SpringBootTest public class MongoApplicationTests {
@Autowired
RecordsDao recordsDao;
@Test
public void contextLoads() {
HashMap<String, Object> map = new HashMap<>();
map.put("1", "lalalla");
map.put("2", "ddddddd");
map.put("3", "cccccc");
map.put("4", "0kkdafkas");
ArrayList<Map<String,Object>> records = new ArrayList<Map<String,Object>>();
for (int i = 0; i < 50; i++) {
records.add(map);
}
long start = System.currentTimeMillis();
System.out.println("看看字段结构"+records);
try {
recordsDao.insertAllMongo(records);
} catch (Exception e) {
System.out.println("异常了:"+e);
// 插入id与库中重复的话会报 org.springframework.dao.DuplicateKeyException 异常
}
long end = System.currentTimeMillis();
// System.out.println("resUsers.size:"+resUsers.size());
System.out.println("批量插入耗时: "+(end-start)+" ms");
// // try { // recordsDao.insertMong(map); // } catch (Exception e) { // System.out.println("异常了:" + e); // } } }
重点在于使用MongoTemplate来实现操作。。。另外查询/更新/删除。批量都可以使用 数据库中存放数据截图如下