Florian Walther
Florian Walther

Reputation: 6951

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?

Upvotes: 17

Views: 6464

Answers (2)

Hilikus
Hilikus

Reputation: 10331

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

Upvotes: 16

Doug Stevenson
Doug Stevenson

Reputation: 317392

@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.

Upvotes: 3

Related Questions