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?
I had the same problem with @AlanH that
animal.getId()
isnull
. And then I just realized my id field had been set as a final field with awither
method. So of coursegetId()
is null since the id field is immutable and thewither
method returns a new object with id.if this is the case: use
animal = template.insert(animal)
.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:
Your animal class looks like this with getters and settings for all fields:
AFTER you have done the insert under
mongoTemplate.insert(animal);
, you can actually call the methodanimal.getId()
and it will return back the ObjectId that was created.