有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我需要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);

目标。toString()将完成这项工作。我可以打开Mongo shell并找到规则对象id,但是如何在java中获得ObjectId呢


共 (1) 个答案

  1. # 1 楼答案

    假设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();