Spring MongoDB在保存后获取插入项目的ID

Madhur Ahuja

我正在使用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。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章