I'm trying to load a full object using db-flow on Android but It doesn't work properly.
The documentation says:
For efficiency reasons we recommend specifying
@ForeignKey(stubbedRelationship = true)
. What this will do is only preset the primary key references into a table object. All other fields will not be set. If you need to access the full object, you will have to call load() for Model, or use the ModelAdapter to load the object from the DB.
And:
Also if you don't specify
@Database(foreignKeyConstraintsEnforced=true)
, calling load() may not have any effect. Essentially without enforcing@ForeignKey
at an SQLite level, you can end up with floating key references that do not exist in the referenced table.
AppDatabase:
@Database(version = AppDatabase.VERSION,
generatedClassSeparator = "_",
foreignKeyConstraintsEnforced = true)
object AppDatabase {
const val NAME = "AppDatabase"
const val VERSION = 1
}
The data entity:
@Parcelize
@Table(database = AppDatabase::class)
data class Checklist(
@PrimaryKey(autoincrement = true)
var id: Long = 0,
@ForeignKeyReference(foreignKeyColumnName = "idReference", columnName = "category_id")
@ForeignKey(onUpdate = ForeignKeyAction.CASCADE,
onDelete = ForeignKeyAction.CASCADE,
stubbedRelationship = true)
var module: Module? = null,
}
The dao function:
suspend fun save(checklist: Checklist) {
withContext(ioContext) {
modelAdapter<Checklist>().save(checklist)
}
}
The retrieve function:
suspend fun getChecklist(id: Long): Checklist? = withContext(ioContext) {
SQLite.select()
.from(Checklist::class.java)
.where(Checklist_Table.id.`is`(id))
.querySingle()
}
Here is the problem. When I load the Checklist object, the module attribute isn't loaded which is referenced on Checklist.
fun loadChecklist(checklist: Checklist){
modelAdapter<Checklist>().load(checklist)
if(checklist.module != null)
System.out.print("module loded")
else
System.out.print("module isn't loaded")
}
I fix the problem using the function:
modelAdapter<Module>().load(checklist.module, FlowManager.getWritableDatabase(AppDatabase::class.java))
Now I have the module loaded.