【问题标题】:Android Koltin Room DatabaseAndroid Kotlin 房间数据库
【发布时间】:2022-01-24 23:35:39
【问题描述】:

我是 android 开发人员的新手,我尝试使用 kotlin room 数据库。我做了一个购物应用程序,但我遇到了问题。我使用表格就像我发布Table that i use。我尝试使用左连接将 table_2 嵌入到 table_1,但正如您在 table_2 中看到的那样,有相同的行具有不同的条形码编号。我试图选择其中之一,但我失败了。每次我这样做时,一行中的 product_id 都有很多条码。所以我需要建议。提前感谢您的帮助。

【问题讨论】:

  • 请使用更具描述性的标题

标签: android database sqlite kotlin android-room


【解决方案1】:

有一个 POJO(不是表的实体),您使用 @Embedded 注释嵌入 table_1(父级)并使用 @Relation 注释与 table_2(子级)列表相关。

例如

data class Table_1WithTable_2List(
    @Embedded
    val table_1: Table_1,
    @Relation(
        entity = Table_2::class,
        parentColumn = "productId",
        entityColumn = "productId"
    )
    val table_2List: List<Table_2>
)

然后使用 Dao,例如 :-

更正:-

@Transaction
@Query("SELECT * FROM table_1")
fun getAllTable_1sWithAListOfTheTable_2Children(): List<Table_1WithTable_2List>

工作示例

考虑 table_1 填充有:-

table_2 和 :-

然后:-

    for(t1t2: Table_1WithTable_2List in dao.getAllTable_1sWithAListOfTheTable_2Children()) {
        Log.d("TABLE_1INFO","Product is ${t1t2.table_1.productName} it has ${t1t2.table_2List.size} Table2s. They are:-")
        for (t2: Table_2 in t1t2.table_2List) {
            Log.d("TABLE_2INFO","\tBarcode is ${t2.productBarcode}")
        }
    }

导致日志显示:-

D/TABLE_1INFO: Product is Product1 it has 2 Table2s. They are:-
D/TABLE_2INFO:  Barcode is BarcodeA
D/TABLE_2INFO:  Barcode is BarcodeX
D/TABLE_1INFO: Product is Product2 it has 1 Table2s. They are:-
D/TABLE_2INFO:  Barcode is BarcodeY
D/TABLE_1INFO: Product is Product3 it has 3 Table2s. They are:-
D/TABLE_2INFO:  Barcode is BarcodeZ
D/TABLE_2INFO:  Barcode is BarcodeZZ
D/TABLE_2INFO:  Barcode is BarcodeZZZ
D/TABLE_1INFO: Product is product4 it has 0 Table2s. They are:-

【讨论】:

  • 谢谢你的建议,我会试试的。
  • @mboluk 哎呀搞砸了 Dao 正要编辑答案。
  • @mboluk 已更正。
  • 还有其他方法可以不创建 dao 吗?我实际上有 dao,当我创建一个新函数时,必须更改所有其他函数。所以我想改变查询。有没有过滤之类的方法?
  • @mboluk 一个用@Dao注解的接口(或抽象类)可以有多个功能(道的),你也可以有多个用@Dao注解的接口/抽象类只有多个抽象函数获取带有@Database 注释的类中的Dao。过滤 Table_1 很简单,只需相应地更改 SQL。使用@Relation 过滤 Table_2 将不起作用,因为 Room 构建底层 SQL 以获取所有相关的 Table_2(可以完成,但肯定是另一个问题)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-21
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多