user4798115
user4798115

Reputation:

spring-data-mongo, how to return _id back for saved objects from mongo?

I am newbie to the Spring Data mongo. I have documents which has same FirstName say John, but MiddleName and LastName are different.

Also from UI, some students populating data (feeding data via forms) which has also FirstName say John and again MiddleName and LastName would be different.

Now, when I am saving User Object (which has FirstName, MiddleName, LastName, Age, Sex etc..etc..) into mongo using MongoTemplate. I need to return back "_id" (which mongo create by default if we don't provide it explicitly) of those each saved User object.

Could you please provide any example / guidance? Please help.

Upvotes: 2

Views: 5539

Answers (2)

Josef Prochazka
Josef Prochazka

Reputation: 1283

If you are saving with mongo template your object Id will be set after insertion (as Oliver Gierke has writen) of the object so you can do it like this.

//User object annotated with @Document 
User user = new User(String name);
user.setWhatever(something);
mongoTemplate.save(user);
//now the user object should be populated with generated id;
return  user.getId();

but you can use normal CrudRepository and use it with

<mongo:repositories base-package="your.package" />

Upvotes: 4

Oliver Drotbohm
Oliver Drotbohm

Reputation: 83161

Spring Data MongoDB will automatically populate the identifier property of your domain object with the generated identifier value.

@Document
class User {

  ObjectId id; // by convention, use @Id if you want to use a different name
  String firstname, lastname;
  …
}

If an object of this class is persisted with the id property set to null, the object will have the property set after it has been persisted via MongoTempalte.

All of this is also described in the reference documentation.

Upvotes: 1

Related Questions