Reputation: 894
I need the String representation of the ID of an object that is in my Mongo.
QuestionDTO questionDTO = new QuestionDTO ();
HashMap<String, QuestionDTO > nodes = new HashMap<>();
nodes.put("foo", QuestionDTO );
Rule rule = new Rule("my rule", nodes);
ruleRepository.save(rule);
ObjectId.toString() will do the job. I can open the Mongo shell and find the rule object id but how do I get the ObjectId in java ?
Upvotes: 0
Views: 298
Reputation: 4363
Supposing ruleRepository is an implementation of MongoRepository, save method returns your entity, with generated _id. So update your code to get returned object, as advised in the save method description :
@Id
@JsonProperty
private String id;
@JsonProperty
private String name;
@JsonProperty
private String cat;
public String getId() {
return id;
}
QuestionDTO questionDTO = new QuestionDTO ();
HashMap<String, QuestionDTO > nodes = new HashMap<>();
nodes.put("foo", QuestionDTO );
Rule rule = new Rule("my rule", nodes);
rule= ruleRepository.save(rule); //Note the variable re-assignement
String id = rule.getId();
Upvotes: 2