问题:
我们都知道 mongodb 有两种添加数据的方式 一种 就是 save 方法 另外一种 insert 方法
这里两个方法 唯一的区别就是
insert:当主键"_id"在集合中存在时,不做任何处理。 抛异常
save:当主键"_id"在集合中存在时,进行更新。 数据整体都会更新 ,新数据会替换掉原数据> save 方法 需要遍历列表,一个个插入, 而 insert 方法 是直接批量插入
那么
Springboot-mongodb MongoRepository接口 并未提供 insert 方法 ,只提供了 save 方法 。 而 数据比较多 想使用 insert 批量插入 提高速度 怎么办
解决方法:
第一种 使用 原生 MongoTemplate 类 进行处理 想怎么样就 怎么样 。 比如 ID 自增
@Component
public>
{
@Autowired
private MongoTemplate mongoTemplate;
/** * 通过两张表来做的> *
@return 返回 最新的ID*/ public Integer getId()
{
Query query = new Query(Criteria.where("_id").is("productid"));
Update update = new Update().inc("sequence_value", 1);
Counters m = mongoTemplate.findAndModify(query, update, Counters.class);
return m.getSequence_value();
}
public void insertList(List<ThothOrder> t)
{
mongoTemplate.insertAll(t);
}
}
第二种 看 MongoRepository 接口 的具体实现类 SimpleMongoRepository<T,>
public>
private final MongoOperations mongoOperations;private final MongoEntityInformation<T,>
public SimpleMongoRepository(MongoEntityInformation<T,>Assert.notNull(mongoOperations); Assert.notNull(metadata);
this.entityInformation = metadata;this.mongoOperations = mongoOperations; }
public <S extends T> S save(S entity) { Assert.notNull(entity,
"Entity must not be null!");// 关键在这里 isNow 这个方法的实现类非常不好找
// 判断一下主键的值是否存在,存在返回false,反正为true.通过 处理类 设置主键Id的,就会走save,而不是insert了 if(this.entityInformation.isNew(entity)) {
this.mongoOperations.insert(entity, this.entityInformation.getCollectionName());
} else {
this.mongoOperations.save(entity, this.entityInformation.getCollectionName());
}
return entity;
}
public <S extends T> List<S> save(Iterable<S> entities) {
Assert.notNull(entities, "The given Iterable of entities not be null!");
List<S> result = convertIterableToList(entities);
boolean allNew = true;
Iterator var4 = entities.iterator();
Object entity;
while(var4.hasNext()) {
entity = var4.next();
// 关键还是在这里
if(allNew && !this.entityInformation.isNew(entity)) {
allNew = false;
}
}
// 如果集合中 并未有 设置ID 主键的值 那么就 调用 insertAll 做批量插入
if(allNew) {
this.mongoOperations.insertAll(result);
} else {
var4 = result.iterator();
// 否则 就 遍历集合 逐个 插入 或更新
while(var4.hasNext()) {
entity = var4.next();
this.save(entity);
}
}
return result;
}
}
最后
强烈推荐 使用 myeclipse 或者 eclipse 开发的 亲们, 是适合 体验一下 >
运维网声明
1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网 享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com