Flo*_*her 7 android firebase google-cloud-firestore
没有关于如何在自定义Java对象中正确存储Firestore文档的自动生成ID的真实文档。检索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;
}
}
Run Code Online (Sandbox Code Playgroud)
加载数据:
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);
}
}
});
}
Run Code Online (Sandbox Code Playgroud)
我的问题:
1)@Exclude
on getter方法是否足够?我也应该将其添加到设置器中吗?还是要现场申报?
2)我是否缺少在模型类中处理文档ID的更便捷方法?
Hil*_*kus 13
现在终于有一个正确的方法来做到这一点。您只需要用 注释该字段@DocumentId
。更多细节
在你的情况下
public class Note {
@DocumentId
private String documentId;
...
}
Run Code Online (Sandbox Code Playgroud)
正如@fuadj 所指出的,这从 Cloud Firestore 版本 20.2.0 开始可用
getter 上的@Exclude就足够了。
确实没有一种“正确”的方法来完成你正在做的事情。看起来您正在按照您需要的方式处理此问题,这很好。
如果您希望看到一种将文档 ID 映射到 javabean 的更正式和自动化的方法,这听起来像是您可以提交的功能请求。也许可以添加另一个注释来指示您想要使用哪个字段来存储 ID。
归档时间: |
|
查看次数: |
1521 次 |
最近记录: |