Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore - How to properly store the document ID in the model class?

There is no real documentation about how to properly store the auto-generated ID of a Firestore document in a custom Java object. Retrieving the ID is easy, but how to properly store it to avoid redundancy.

This is my approach:

Model class:

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;
    }
}

Load data:

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);
                    }
                }
            });
}

My questions:

1) Is the @Exclude on the getter method enough? Should I also add it to the setter? Or to the field declaration?

2) Am I missing a more convenient way to handle the document ID in a model class?

like image 212
Florian Walther Avatar asked Apr 16 '18 20:04

Florian Walther


2 Answers

There's finally a proper way to do this now. You just need to annotate the field with @DocumentId. More details

In your case

public class Note {
   @DocumentId
   private String documentId;
   ...
}

As noted by @fuadj, this is available starting on Cloud Firestore version 20.2.0

like image 64
Hilikus Avatar answered Oct 02 '22 03:10

Hilikus


@Exclude on the getter is sufficient.

There is not really a "proper" way to do what you're doing. It looks like you're handling this the way you need, and that's fine.

If you would like to see a more formalized and automated way of mapping the document ID into a javabean, that sounds like a feature request you could file. Maybe another annotation could be added that indicates which field you would like to use to store the ID.

like image 20
Doug Stevenson Avatar answered Oct 02 '22 05:10

Doug Stevenson