I’m trying to locally cache a model I’m getting from an API, the model is as follows:
data class Subject(
val id: Long,
val meanings: List<Meaning>
// It has more fields, but they are not relevant
)
data class Meaning(
val meaning: String,
val primary: Boolean,
val acceptedAnswer: Boolean
)
As you can see, the Meaning
model is quite simple and only consists of types supported by Objectbox. The Meaning
s are entirely unique for each Subject
, they are not shared between subjects. More importantly, every time I get updated data from the API and want to overwrite the existing subjects, I want to do so for all the nested objects as well. I need Subject
and all the objects nested inside of it to be treated as one thing.
It seems that there is no way to create an equivalent Objectbox @Entity, with a nested object field, or a field that is a list of objects, without using relations. The problem that I am encountering with relations, is that they cannot be simply overwritten as I’ve described above.
If I have the following entities defined:
@Entity
data class SubjectEntity(
@Id var id: Long = 0,
@Index
@Unique(onConflict = ConflictStrategy.REPLACE)
var apiId: Long = 0,
) {
lateinit var meanings: ToMany<MeaningEntity>
}
@Entity
data class MeaningEntity(
@Id var id: Long = 0,
val meaning: String = "",
val primary: Boolean = false,
val acceptedAnswer: Boolean = false
)
…then trying to update the meanings like:
subjectEntity.meanings.apply {
clear()
addAll(...)
}
subjectBox.put(subjectEntity)
..keeps all the meanings that were previously there in the box of MeaningEntity
, which I don’t need. This means I have to manually remove objects from the MeaningEntity
box, only the ones I need to be removed in their corresponding subjects, which seems like too much work for something so simple.
Clearly relations aren’t what i need. They make no sense for this use-case, and using them feels like I’m creating a second “table” that I need to manage which completely defeats the point of this being a NoSQL database.
Is there a better way to do this?