错误查询 一对多关系室

Posted

技术标签:

【中文标题】错误查询 一对多关系室【英文标题】:Bad query One-to-many relationship room 【发布时间】:2022-01-23 20:15:40 【问题描述】:

我对房间查询有疑问。我有主题数据类,以 id 作为主键:

@Entity(tableName = "themes_table")
data class Theme(
        @PrimaryKey
        var id: String = "",
        var specialityId: String = "",
        var details: String = "",
        var lastUpdated: Long = -1,
        var title: String = ""
)

我有 Question 数据类,它有字段 themeIds (ArrayList):

@Entity(tableName = "questions_table")
data class Question(
        val correctAnswer: String = "",
        @PrimaryKey
    val id: String = "",
        val specialityId: String = "",
        val imageFileName: String = "",
        val imageLastUpdated: String = "",
        val lastUpdated: Long = -1,
        var isFavourite: Boolean = false,
        var isExamined: Boolean = false,
        var isLearned: Boolean = false,
        var isCorrect: Boolean = false,
        var isMistake: Boolean = false,
        var selectedAnswer: String = "",
    val order: Int = -1,
        val text: String = "",
        @TypeConverters(ArrayListConverter::class)
    val themeIds: ArrayList<String> = arrayListOf(),
        @TypeConverters(MapConverter::class)
    var variants: MutableMap<String, String> = mutableMapOf()
): Serializable

我想获取带有以下问题的主题列表:

data class ThemeWithQuestions(
        @Embedded
        var theme: Theme,
        @Relation(parentColumn = "id", entityColumn = "themeIds", entity = Question::class)
        var questionsList: MutableList<Question> = mutableListOf()
)

@Transaction()
@Query("SELECT * FROM themes_table")
fun getThemesWithQuestions(): MutableList<ThemeWithQuestions>

但是这个查询只得到主题,问题列表总是空的。问题可能出在此查询中吗?我应该在上面加上“IN”声明吗?我该如何解决?

【问题讨论】:

您所做的基本上与关系 sql 范式背道而驰,并且在 nosql dbs 中很容易实现。正确的方法是从 Question 中删除 themeIds,然后创建一个仅包含 themeId 和 questionId 作为复合主键的表,并基于此进行查询。 @RahulRawat ,抱歉,我不知道该怎么做)你能帮我吗? Question里面的variant map有什么用? 【参考方案1】:

尝试查询:

@Query("SELECT * FROM themes_table WHERE id = :id")
fun getThemesWithQuestions(id: Int): MutableList<ThemeWithQuestions>

检查一下这可能会有所帮助

How to handle one to many entity relationship with room and recyclerviews?

【讨论】:

谢谢,但我需要获取一个 ThemeWithQuestion 数组 你能用 AddQuestion 方法更新帖子并查询这个吗?

以上是关于错误查询 一对多关系室的主要内容,如果未能解决你的问题,请参考以下文章

MyBatis高级篇 - 关联查询(一对多)

gorm 关系一对一,一对多,多对多查询

gorm 关系一对一,一对多,多对多查询

如何在春季配置多对一和一对多关系? Hibernate会无限调用同一查询

mybatis 一对一,一对多,多对多关系映射查询操作

sql 一对多的查询