javaandroidfirebasegoogle-cloud-platformgoogle-cloud-firestore

Why is Firestore not mapping a field of type private?


I have the following structure in Firestore:

enter image description here

The map called lecturaBreve corresponds to the following class:

public class BiblicalShort extends Biblical {
    private LHResponsoryShort responsorio;

    public BiblicalShort() {
    }

    public void setResponsorio(LHResponsoryShort responsorio) {
        this.responsorio = responsorio;
    }
}

And the map called responsorio would correspond to this class: public class LHResponsoryShort { protected Integer responsoryID; protected String text; protected Integer type;

    public Integer getResponsoryID() {
        return responsoryID;
    }

    public void setResponsoryID(Integer responsoryID) {
        this.responsoryID = responsoryID;
    }

    public String getText() {
        return this.text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Integer getType() {
        return this.type;
    }

    public void setType(Integer type) {
        this.type = type;
    }
    
    // ...
}

My problem is that when I try to map the Firestore response to these classes, it does not map the responsorio object correctly.

If I define the property as public, the mapping is done correctly:

public LHResponsoryShort responsorio;

Why is the mapping not done to the property declared private? Are private properties not mapped to a properly defined setter method? In this case:

public void setResponsorio(LHResponsoryShort responsorio) {
        this.responsorio = responsorio;
}

Solution

  • In order to be able to map the fields in a Java class with the fields in a Firestore document, the Firestore SDK for Android needs to use public accessors, which can be either the public fields in the class or the public getters/setters. This is a well-known convention called the JavaBean convention.

    Checking your BiblicalShort class, I can see that the class contains a public setter for the responsorio field, but it does not contain a public getter for the field. This means that the Firestore SDK will be able to set the responsorio field but it will not be able to read it.

    One more important thing to remember is that the name of the fields that exist in your class must match the name of the properties that exist in your database, otherwise you should use an annotation called PropertyName in front of the getter.

    When it comes to the private keyword, please remember that in Java, the private access modifier is used to restrict access to a class member (variable, method, or constructor) so that it can only be accessed within the same class. So in your case, you should always use the public access modifier.