I'm attempting to develop an Android application that consumes a REST API through Retrofit and caches the received results in a Room DB. The way I'm planning to implement this behaviour is by having the local database created by Room to act as my SSoT (Single Source of Truth) for my data through my Repository.
My problem arises when I try to implement the Room configuration and behaviour for a single UserEntity (one of my models). This Database entity contains the exact same atomic information as the Retrofit User model (id, username, email, description) and doesn't contain a server response or photo URL field. And now, when I have two models and I need to create a method in the Repository to return a LiveData instance, I'm not sure how to fit both types without manually converting them (because once I'd retrieve a User model from a Retrofit request and update the Room DB which takes UserEntity parameters but another time I might just fetch the user data from the cache).
I'm wondering if there's any way to simply have one model for both Retrofit and Room operations or if I need to convert my Retrofit server response model to my Room DB entity manually. Is there no possibility to have both the @SerializedName and @ColumnInfo annotations in the model (and, if need be for other models, use @Ignore to make Room ignore unnecessary fields)? Or would that just confound the entire model and make it unusable?
Code excerpts for further insight:
UserEntity.java (Room model)
@Entity(tableName = "users")
public class UserEntity {
@PrimaryKey
@NonNull
private int id; // id is fetched from network response - not autogenerated
@ColumnInfo(name = "username")
private String username;
@ColumnInfo(name = "description")
private String description;
@ColumnInfo(name = "email")
private String email;
public UserEntity(int id, String username, String description, String email) {
this.id = id;
this.username = username;
this.description = description;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
User.java (Retrofit response)
public class User extends Model implements Parcelable {
@SerializedName("id")
@Expose
@Nullable
private Integer id;
@SerializedName("username")
@Expose
@Nullable
private String username;
@SerializedName("description")
@Expose
@Nullable
private String description;
@SerializedName("email")
@Expose
@Nullable
private String email;
@SerializedName("photo_url")
@Expose
@Nullable
private String photoUrl;
// constructors, getters & setters, & implementations. . .
}
Thank you in advance!