使用 DBFlow 加载对象

Load object with DBFlow

我正在尝试在 Android 上使用 db-flow 加载完整对象,但它无法正常工作。

文档 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.

并且:

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.

应用程序数据库:

@Database(version = AppDatabase.VERSION, 
        generatedClassSeparator = "_", 
        foreignKeyConstraintsEnforced = true)

object AppDatabase {

    const val NAME = "AppDatabase"
    const val VERSION = 1
}

数据实体:

@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,

}

dao函数:

suspend fun save(checklist: Checklist) {
    withContext(ioContext) {
        modelAdapter<Checklist>().save(checklist)
    }
}

检索函数:

suspend fun getChecklist(id: Long): Checklist? = withContext(ioContext) {
        SQLite.select()
                .from(Checklist::class.java)
                .where(Checklist_Table.id.`is`(id))
                .querySingle()
    }

问题来了。当我加载 Checklist 对象时,未加载在 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")
}

我使用函数修复了问题:

modelAdapter<Module>().load(checklist.module, FlowManager.getWritableDatabase(AppDatabase::class.java))

现在我已经加载了模块。