【问题标题】:how to autoGenearte _id instead of mongoDB ObjectId()如何自动生成 _id 而不是 mongoDB ObjectId()
【发布时间】:2016-04-07 08:04:30
【问题描述】:

如何生成 "_id" : "01A63D2B-1724-456E-B2C0-3B3729951654" 而不是 "_id" : ObjectId("570602c46399e320c3022c6b")

我的Student.class

@Entity("student")
public class Student {
@Id
private String Id;

private long studentId;
private String studentName;
private String qualification;

public Student(){

}

public Student(long studentId, String studentName, String qualification) {
    this.studentId = studentId;
    this.studentName = studentName;
    this.qualification = qualification;
}

public long getStudentId() {
    return studentId;
}

public void setStudentId(long studentId) {
    this.studentId = studentId;
}

public String getStudentName() {
    return studentName;
}

public void setStudentName(String studentName) {
    this.studentName = studentName;
}

public String getQualification() {
    return qualification;
}

public void setQualification(String qualification) {
    this.qualification = qualification;
}
}

将 JSON 数据添加到 MOngoDB 的功能

public void importFromJsonToMongoDB(File file) throws FileNotFoundException{

        try{
        String strJson = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
        JSONArray jsonArr = new JSONArray(strJson);

        for (int i = 0; i < jsonArr.length(); i++)
        {
            JSONObject jsonObj = jsonArr.getJSONObject(i);
            String str = jsonObj.toString();
            ObjectMapper mapper = new ObjectMapper();
            Student std = mapper.readValue(str, Student.class);
            sr.save(std);
        }
        }catch (Exception e) {
        e.printStackTrace();
        System.out.println("Error While parsing data");
    }

* 如何自动生成 id?而不是 MongoDb 生成它。

【问题讨论】:

  • 保存文档前需要设置_id值

标签: java mongodb uniqueidentifier


【解决方案1】:

我认为您需要在 MongoDB 中插入文档时添加“_id”字段。由于您没有指定任何“_id”字段,它将由 MongoDB 自动生成。也可以根据自己的喜好使用mongodb的getNextSequence()方法生成id。

注意:StudentID 和 _id 是同一文档中的两个不同实体。

我希望这些链接对您有用: https://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/

【讨论】:

    【解决方案2】:

    用下面的一个替换现有的 NO-arg 构造函数 学生班

    public Student(){
    
      super();
      id = UUID.randomUUID().toString();
    }
    
    • 这将生成随机 id 而不是 MongoDB ObjectId

    【讨论】:

    • 对我来说这是可行的,并将记录保存在具有自定义 ID 的数据库中。但之后它会抛出ClassCastExceptionLong 不能转换为Integer 任何输入?问题link
    猜你喜欢
    • 1970-01-01
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-28
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多