【问题标题】:how to use @Relation in Room如何在房间中使用@Relation
【发布时间】:2021-02-20 06:11:41
【问题描述】:
{
        "id": 7,
        "title": "Reading monthly hot list in January",
        "img_url": "http://image.wufazhuce.com/FteWZbumJ0vugA_oF-tjk9OxOhT5",
        "contents": [
            {
                "id": "4582",
                "title": "How to say goodbye",
                "subtitle": "Gengsheng Su",
                "category": 1,
                "cover": "http://image.wufazhuce.com/FnBm-nZ-fQIit227taKI9Tue_9sx?imageView2/1/w/120/h/120",
                "maketime": "2021-01-20 06:00:00",
                "weight": 15
            },
            {
                "id": "4567",
                "title": "Go to RT Mart",
                "subtitle": "Zhanhei Wang",
                "category": 1,
                "cover": "http://image.wufazhuce.com/Fv2ZTzdL0LjfzB8q5N_mp_7h5Ti8?imageView2/1/w/120/h/120",
                "maketime": "2021-01-09 06:00:00",
                "weight": 14
            },
            {
                "id": "4560",
                "title": "cLOUD MADE BY RAIN",
                "subtitle": "GongChen",
                "category": 1,
                "cover": "http://image.wufazhuce.com/FnZhpbcENaSm6Fmnjfxaz0oAgXzo?imageView2/1/w/120/h/120",
                "maketime": "2021-01-01 06:00:00",
                "weight": 13
            }
        ]
    }

我想用这个 json 转换成 bean,并将其存储在我的 Room 中。 但是我不知道怎么存放。可能我对Room不熟悉。

我尝试使用它

@Entity(tableName = "rebang_cache")
data class ReBang(
        @PrimaryKey
        var id: Int,
        var title: String?,
        var img_url: String?,
        @Relation(
                parentColumn = "id",
                entityColumn = "id")
        val contents: List<ContentBean>?) {

    @Entity
    data class ContentBean(@PrimaryKey
                           var id: String,
                           var title: String?,
                           var subtitle: String?,
                           var category: Int?,
                           var cover: String?,
                           var maketime: String?,
                           var weight: Int?)
}

但它是错误的。我想知道如何实现它。

我认为这是一个很好的问题!

【问题讨论】:

  • 嗨@pnkj可以分享错误信息
  • 哦,我认为错误信息不重要,因为这是我的使用错误。

标签: android kotlin android-room android-jetpack


【解决方案1】:

你需要先定义父子实体类:

@Entity(tableName = "rebang_cache")
data class ReBang( 
    @PrimaryKey
    val id: Long,
    val title: String
    //...)

@Entity
data class ContentBean(
    @PrimaryKey val id: Long,
    //parent model reference id
    val rebangId: Long,
    val title: String,
    //..)

然后使用@Relation注解定义一对多关系

data class ReBangWithContents(
    @Embedded val rehang: ReBang,
    @Relation(
        parentColumn = "id"
        entityColumn = "rebangId"
    )
    val contents: List<ContentBean>
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 2014-02-23
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多