Spring MongoDB在保存后获取插入项目的ID [英] Spring mongodb get ID of inserted item after Save
问题描述
我正在使用Spring MongoDb.
I am working with Spring MongoDb.
我使用insert
方法创建各种实体:
http://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/MongoOperations.html#insert-java.lang.Object-
I create various entities using insert
method:
http://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/MongoOperations.html#insert-java.lang.Object-
但是,所有方法都返回void
.我需要返回插入文档的ObjectId
.
However, all methods return void
. I need to return the ObjectId
of the inserted document.
获得它的最好方法是什么?
What is the best way to get it?
推荐答案
这很有趣,我想分享一下.我只是在上面的BatScream评论的帮助下找到了解决方案:
This is pretty interesting and thought I would share. I just figured out the solution for this with the help of BatScream comment above:
您将创建一个对象并将其插入到MongoDB中:
You would create an object and insert it into your MongoDB:
Animal animal = new Animal();
animal.setName(name);
animal.setCat(cat);
mongoTemplate.insert(animal);
您的动物类如下所示,其中包含所有字段的吸气剂和设置:
Your animal class looks like this with getters and settings for all fields:
public class Animal {
@Id
@JsonProperty
private String id;
@JsonProperty
private String name;
@JsonProperty
private String cat;
public String getId() {
return id;
}
}
在mongoTemplate.insert(animal);
下完成插入后,您实际上可以调用方法animal.getId()
,它将返回创建的ObjectId.
AFTER you have done the insert under mongoTemplate.insert(animal);
, you can actually call the method animal.getId()
and it will return back the ObjectId that was created.
这篇关于Spring MongoDB在保存后获取插入项目的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!