Georgi Michev
Georgi Michev

Reputation: 894

How to get objectID of object in database

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

Answers (1)

matthPen
matthPen

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 :

Add id field to Rule object :

@Id
@JsonProperty
private String id;
@JsonProperty
private String name;
@JsonProperty
private String cat;

public String getId() {
    return id;
}

Update your code :

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

Related Questions