Spring mongodb get ID of inserted item after Save

試著忘記壹切 提交于 2019-12-04 01:50:22
Simon

This is pretty interesting and thought I would share. I just figured out the solution for this with the help of BatScream comment above:

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;
    }
}

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.

Philip

I had the same problem with @AlanH that animal.getId() is null. And then I just realized my id field had been set as a final field with a wither method. So of course getId() is null since the id field is immutable and the wither method returns a new object with id.

if this is the case: use animal = template.insert(animal).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!