我一直在研究将Room数据库与Kotlin整合在一起的新项目,而且我遇到了一些问题。我有一个Category实体,其中包含一个Question实体列表。问题实体本身包含答案实体列表。我想查询数据库并获取包含问题及其答案的所有类别。使用我所拥有的解决方案,它返回一个仅包含第一个类别的列表。如果我将它更改为Flowable调用它返回相同但onNext方法触发多次并最终获取所有类别(每个都在列表中),但我想一次性获取它们。到目前为止我做了什么:
实体:
@Entity(tableName = TABLE_CATEGORIES)
data class Category (
@PrimaryKey(autoGenerate = true)
var id: Int = 0,
var name: String? = ""
)
@Entity(tableName = TABLE_QUESTIONS)
data class Question (
var text: String? = "",
@PrimaryKey(autoGenerate = true)
var id: Int = 0,
var categoryId: Int? = 0,
var typeId: Int? = 0,
var extraData: String? = "",
@Ignore
var answers: List<Answer>
)
@Entity(tableName = TABLE_ANSWERS)
data class Answer (
@PrimaryKey(autoGenerate = true)
var id: Int = 0,
var text: String? = "",
var isCorrect: Boolean? = false,
var questionId: Int = 0
)
关系类:
class QuestionAnswersJoin {
@Embedded
var question: Question = Question()
@Relation(parentColumn = "id", entityColumn = "questionId")
var answers: List<Answer> = ArrayList()
}
class CategoryQuestionsAnswersJoin {
@Embedded
var category: Category = Category()
@Relation(parentColumn = "id", entityColumn = "categoryId", entity = Question::class)
var questionsAnswers: List<QuestionAnswersJoin> = ArrayList()
}
查询:
@Transaction
@Query("SELECT * FROM $TABLE_CATEGORIES")
fun getCategories() : Single<List<CategoryQuestionsAnswersJoin>>