如何使用autoGenearte _id代替mongoDB ObjectId()

时间:2016-04-07 08:04:31

标签: java mongodb uniqueidentifier

如何生成" _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生成它。

1 个答案:

答案 0 :(得分:0)

将现有的NO-arg构造函数替换为下面的一个 的 Student.class

public Student(){

  super();
  id = UUID.randomUUID().toString();

}

  • 这将生成随机ID而不是MongoDB ObjectId