Spring MongoRepository正在更新或插入而不是插入 [英] Spring MongoRepository is updating or upserting instead of inserting

查看:947
本文介绍了Spring MongoRepository正在更新或插入而不是插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用:

org.springframework.data.mongodb.repository.MongoRepository

我从空DB开始,用 _id = 1234 创建一个对象例如,并将一些其他字符串字段设置为 hello ,然后执行:

I start with an empty DB and create an object with _id = 1234 for example, and set some other String field to hello for example, and then do:

repository.save(object);

一切都很好,它将文档保存在MondoDB中。

All is well, it saves the document in MondoDB.

我创建一个新对象,设置相同的 _id = 1234 ,但将另一个String字段设置为 world 然后到另一个保存:

I create a NEW object, set the same _id = 1234 but set the other String field to world and then to another save :

repository.save(newObject);

结果:保存有效但更新原始对象。

Results : the save works but updates the original object.

预期结果:这应该会因 DuplicateKeyException 而失败,因为 _id 是唯一的,我使用2个单独的每次保存时的对象。

Expected results: This should fail with a DuplicateKeyException as _id is unique and I am using 2 separate objects when doing each save.

春天的缺陷或我做错了什么???

Defect in spring or am I doing something wrong ???

推荐答案

保存,根据定义,应该更新upsert样式中的对象,如果存在则更新,如果不存在则插入。
阅读MongoDb save 操作文档。 save /rel =noreferrer>网站

Save, by definition, is supposed to update an object in the upsert style, update if present and insert if not. Read the save operation documentation on the MongoDb website

mongodb中的插入操作具有您期望的行为,但是来自MongoRepository文档看起来插入委托保存,所以它不会有任何区别。但你可以尝试一下,看看它是否适合你。否则你可以先做一个get来检查对象是否存在,因为它是一个索引查找它会很快。

The insert operation in mongodb has the behavior you expect, but from the MongoRepository documentation it appears that insert is delegated to save so it won't make any difference. But you can give that a try and see if it works for you. Otherwise you can just do a get before to check if the object exists, since it is an index lookup it will be fast.

这篇关于Spring MongoRepository正在更新或插入而不是插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆