Kieran M
Kieran M

Reputation: 461

Should Foreign Keys have corresponding getters and setters in Room Persistence Library?

The following code shows that I have created an entity with the class name UserGeneral. Each of the columns unique to this entity have corresponding getters and setters. However, the foreign keys have no getters and setters. Do I need to provide getters and setters for user_details_id and user_location_id?

@Entity(
    tableName = "User_General",
    indices = {
        @Index("user_details_id"),
        @Index("user_location_id")
    },
    foreignKeys = {
        @ForeignKey(
            entity = UserDetails.class,
            parentColumns = "user_details_id",
            childColumns = "user_details_id"
        ),
        @ForeignKey(
            entity = UserLocation.class,
            parentColumns = "user_location_id",
            childColumns = "user_location_id"
        )
    }
)
public class UserGeneral {

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "user_general_id")
    private int user_general_id;

    @ColumnInfo(name = "first_name")
    private String first_name;

    @ColumnInfo(name = "last_name")
    private String last_name;

    @ColumnInfo(name = "flagged_delete")
    private boolean flagged_delete;

    @ColumnInfo(name = "user_details_id")
    private int user_details_id;

    @ColumnInfo(name = "user_location_id")
    private int user_location_id;


    public int getUser_general_id() {
        return user_general_id;
    }

    public void setUser_general_id(int user_general_id) {
        this.user_general_id = user_general_id;
    }

    public String getFirst_name() {
        return first_name;
    }

    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }

    public String getLast_name() {
        return last_name;
    }

    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }

    public boolean isFlagged_delete() {
        return flagged_delete;
    }

    public void setFlagged_delete(boolean flagged_delete) {
        this.flagged_delete = flagged_delete;
    }
}

Upvotes: 0

Views: 558

Answers (1)

LLL
LLL

Reputation: 1907

You have to provide getter otherwise you will get something like:

error: Cannot find getter for field.
    private int user_details_id;

setters or passing argument in constructor is used by you. If you don't have such methods then you won't be able to correctly initialize the object. In your case without setters / constructor user_details_id would always be 0 (the same goes for your other foreign key), so all your UserGeneral entities would point to the same user details / location.

Upvotes: 1

Related Questions