使用Room在单个事务中从多个表中获取数据?

时间:2018-08-15 03:45:23

标签: android sqlite android-room

使用房间我正在尝试从两个表(公司和农场)中获取数据到一个列表中。使用commonsware answer创建了基类CompanyFarmBase和两个子类Company和Farm。现在使用示例,我使用以下代码创建了Dao类:

@Query("SELECT * FROM farm_table")
fun getAllFarm(): List<UserModel.Farm>

@Query("SELECT * FROM company_table")
fun getAllCompany(): List<UserModel.Company>

@Transaction
fun getAllCompanyFarm(): List<UserModel.CompanyFarmBase> {
    val result = ArrayList<UserModel.CompanyFarmBase>()

    result.addAll(getAllCompany())
    result.addAll(getAllFarm())

    return result
}

现在,当我尝试构建时,出现以下错误:

dao/FarmDao_Impl.java:100: error: illegal start of expression
  List<UserModel.CompanyFarmBase> _result = FarmDao.DefaultImpls.getAllCompanyFarm(this, );


dagger.internal.codegen.ComponentProcessor was unable to process com.navdeep.di.component.AppComponent because not all of its dependencies could be resolved. Check for compilation errors or a circular dependency with generated code.

请让我知道我哪里出错了。分别查询每个表将提供适当的数据。谢谢!

2 个答案:

答案 0 :(得分:0)

最近也有此问题,传入默认参数将解决此问题。为什么,不知道。

@Transaction
fun getAllCompanyFarm(notUsed: Boolean = true): List<UserModel.CompanyFarmBase> {
    val result = ArrayList<UserModel.CompanyFarmBase>()

    result.addAll(getAllCompany())
    result.addAll(getAllFarm())

    return result
}

答案 1 :(得分:0)

创建单独的数据类来链接这些模型。

data class TaskWithActivities(
    @Embedded var taskEntity: TaskEntity, @Relation(
        parentColumn = "taskId",
        entityColumn = "taskpId"
    ) var activities: List<ActivityEntity>
)

室内实体类写关系: 用于任务(父级)

@Entity(
    tableName = "task_entity",
    primaryKeys = ["taskId", "mandantId"]
)
@kotlinx.parcelize.Parcelize
data class TaskEntity(

对于活动:

@Entity(
    tableName = "activity_entity", indices = arrayOf(Index(value = ["taskpId", "mandantId"])),
    foreignKeys = [
        ForeignKey(
            entity = TaskEntity::class,
            parentColumns = ["taskId", "mandantId"],
            childColumns = ["taskpId", "mandantId"],
            onDelete = NO_ACTION
        )],
    primaryKeys = ["taskpId", "activityId", "mandantId"]
)

现在您可以从两个表中请求:

在你的任务 DAO 中:

@Transaction
@Query("SELECT * FROM task_entity ORDER BY taskDueDateFinish ASC")
fun observeTaskWithActivities(): LiveData<List<TaskWithActivities>>