Java Spring MongoRepository 正在更新或更新而不是插入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29032981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring MongoRepository is updating or upserting instead of inserting
提问by Marc
I'm using a :
我正在使用:
org.springframework.data.mongodb.repository.MongoRepository
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:
我从一个空的 DB 开始,并创建一个对象,_id = 1234
例如,并设置一些其他 String 字段hello
,然后执行:
repository.save(object);
All is well, it saves the document in MondoDB.
一切正常,它将文档保存在 MondoDB 中。
I create a NEW object, set the same _id = 1234
but set the other String field to world
and then to another save :
我创建了一个 NEW 对象,设置相同_id = 1234
但将另一个 String 字段设置为world
,然后设置为另一个 save :
repository.save(newObject);
Results : the save works but updates the original object.
结果:保存有效但更新了原始对象。
Expected results: This should fail with a DuplicateKeyException
as _id
is unique and I am using 2 separate objects when doing each save.
预期结果:这应该会失败,DuplicateKeyException
因为它_id
是唯一的,每次保存时我都使用 2 个单独的对象。
Defect in spring or am I doing something wrong ???
春天的缺陷还是我做错了什么???
采纳答案by tinker
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
根据定义,Save应该以 upsert 样式更新对象,如果存在则更新,如果不存在则插入。阅读save
MongoDb网站的操作文档
The insertoperation 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.
mongodb 中的插入操作具有您期望的行为,但从 MongoRepository 文档看来,插入被委托保存,因此它不会有任何区别。但是您可以尝试一下,看看它是否适合您。否则,您可以先执行 get 来检查对象是否存在,因为它是索引查找,因此速度会很快。
Edit: Check your repository version, insertwas introduced in version 1.7.
编辑:检查您的存储库版本,插入是在1.7版中引入的。
回答by Naveen
the application shall update only when you have @Id annotation for one of the field, after long difficulty had found this
应用程序仅在您对其中一个字段具有 @Id 注释时才更新,经过长时间的困难找到了这个
@Document(collection="bus")
public class Bus {
// @Indexed(unique=true, direction=IndexDirection.DESCENDING, dropDups=true)
@Id
private String busTitle;
private int totalNoOfSeats;
private int noOfSeatsAvailable;
private String busType;
}
but somehow I could not use @Indexed(unique=true, direction=IndexDirection.DESCENDING, dropDups=true)
但不知何故我无法使用 @Indexed(unique=true, direction=IndexDirection.DESCENDING, dropDups=true)