没有关于如何在自定义Java对象中正确存储Firestore文档的自动生成ID的真实文档。检索ID很简单,但如何正确存储以避免冗余。
这是我的方法:
模特课:
public class Note {
private String documentId;
private String title;
private String description;
public Note() {
//public no arg constructor necessary
}
public Note(String title, String description) {
this.title = title;
this.description = description;
}
@Exclude
public String getDocumentId() {
return documentId;
}
public void setDocumentId(String documentId) {
this.documentId = documentId;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
}
加载数据:
public void loadNotes(View v) {
notebookRef.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
List<Note> noteList = new ArrayList<>();
for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
Note note = documentSnapshot.toObject(Note.class);
note.setDocumentId(documentSnapshot.getId());
noteList.add(note);
}
}
});
}
我的问题:
1)getter方法上的@Exclude
是否足够?我还应该将它添加到setter吗?或者到现场申报?
2)我是否错过了更方便的方法来处理模型类中的文档ID?
答案 0 :(得分:4)
现在终于有了一种正确的方法来执行此操作。您只需要用<ComponentThrowingAnError prop1="1" />
注释该字段。 More details
以您的情况
@DocumentId
答案 1 :(得分:3)
没有真正的&#34;正确的&#34;做你正在做的事情的方式。看起来你正在以你需要的方式处理这个问题,那很好。
如果您希望看到更加形式化和自动化的方式将文档ID映射到javabean,这听起来像feature request您可以提交。也许可以添加另一个注释,指示您要用于存储ID的字段。