2016-04-07 65 views
0

如何genearate 「_id」: 「01A63D2B-1724-456E-B2C0-3B3729951654」代替「_id」:物件( 「570602c46399e320c3022c6b」)如何autoGenearte _id代替的MongoDB的ObjectId()

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生成它。

+0

你需要保存文檔 – profesor79

回答

0

替換現有的無參數構造與 Student.class

public Student(){ 

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

}

  • 以下一個,這將產生隨機ID代替的MongoDB的ObjectId
+0

對於我這種工作並持續記錄與自定義ID數據庫之前設置_id谷。但在此之後,它拋出'ClassCastException'說'長'不能轉換爲'整數'任何輸入?問題[鏈接](http://stackoverflow.com/questions/42383336/how-to-use-id-when-using-documentdb-via-mongdb-api-in-spring-data) –

0

我認爲你需要在插入t時添加「_id」字段他在MongoDB中記錄。由於您沒有指定任何「_id」字段,它將自動由MongoDB生成。您還可以使用mongodb的getNextSequence()方法根據您的偏好生成id。

注意:StudentID和_id是同一文檔中的兩個不同實體。

我希望這些鏈接將是對您有用: https://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/