如何获取数据库中对象的objectID

时间:2018-09-03 13:01:13

标签: java spring mongodb

我需要Mongo中对象的ID的字符串表示形式。

    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()将完成此工作。我可以打开Mongo Shell,找到规则对象ID,但是如何在Java中获取ObjectId?

1 个答案:

答案 0 :(得分:2)

假设ruleRepository是MongoRepository的实现,则save方法将返回您的实体,并生成_id。因此,请按照the save method description的建议更新代码以返回对象:

向规则对象添加ID字段:

@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();