Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring mongodb get ID of inserted item after Save

I am working with Spring MongoDb.

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-

However, all methods return void. I need to return the ObjectId of the inserted document.

What is the best way to get it?

like image 659
Madhur Ahuja Avatar asked Nov 18 '14 03:11

Madhur Ahuja


People also ask

How do I get the MongoDB Objectid After insert?

The Mongo driver for NodeJS appends the _id field to the original object reference, so it's easy to get the inserted id using the original object: collection. insert(objectToInsert, function(err){ if (err) return; // Object inserted successfully.

What is the difference between MongoOperations and MongoTemplate?

MongoTemplate provides a simple way for you to save, update, and delete your domain objects and map those objects to documents stored in MongoDB. You can save, update and delete the object as shown below. MongoOperations is the interface that MongoTemplate implements.


2 Answers

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.

like image 102
Simon Avatar answered Oct 22 '22 17:10

Simon


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).

like image 23
Philip Avatar answered Oct 22 '22 19:10

Philip