没有关于如何在自定义 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
是否足够?我还应该将它添加到二传手吗?还是去现场申报?
2) 我是否缺少一种更方便的方法来处理模型类中的文档 ID?
最佳答案
现在终于有了一个合适的方法来做到这一点。您只需要使用 @DocumentId
注释该字段。 More details
在你的情况下
public class Note {
@DocumentId
private String documentId;
...
}
正如@fuadj 所指出的,这从 Cloud Firestore 版本 20.2.0 开始可用
关于android - Firestore - 如何在模型类中正确存储文档 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49865690/