我需要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?
答案 0 :(得分:2)
假设ruleRepository是MongoRepository的实现,则save方法将返回您的实体,并生成_id。因此,请按照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();