我正在使用 Spring MongoDb。
insert
我使用方法
创建各种实体:http: //docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/MongoOperations.html#insert-java.lang.Object -
但是,所有方法都返回void
. 我需要返回ObjectId
插入的文档。
获得它的最佳方法是什么?
我正在使用 Spring MongoDb。
insert
我使用方法
创建各种实体:http: //docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/MongoOperations.html#insert-java.lang.Object -
但是,所有方法都返回void
. 我需要返回ObjectId
插入的文档。
获得它的最佳方法是什么?
这很有趣,我想我会分享。我刚刚在上面的 BatScream 评论的帮助下找到了解决方案:
您将创建一个对象并将其插入到您的 MongoDB 中:
Animal animal = new Animal();
animal.setName(name);
animal.setCat(cat);
mongoTemplate.insert(animal);
你的动物类看起来像这样,所有字段的 getter 和设置:
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。
我对@AlanH 有同样的问题,animal.getId()
即null
. 然后我才意识到我的 id 字段已被设置为带有wither
方法的最终字段。所以当然getId()
是 null,因为 id 字段是不可变的,并且该wither
方法返回一个带有 id 的新对象。
如果是这种情况:使用animal = template.insert(animal)
.