【问题标题】:How to save objects in room the database. Kotlin Android如何将房间中的对象保存在数据库中。 Kotlin 安卓
【发布时间】:2021-03-12 15:35:45
【问题描述】:

我正在尝试将对象保存在房间数据库中。

我想保存在数据库中的个人资料对象类:

class Profile(
 val exampleString : String = "Example String",
 val exampleStringTwo : String = "Example String Two",
 val subObjectsList : ArrayList<SubObjecst> = ArrayList()
)

配置文件对象包括具有此结构的子对象的 Arraylist:

class SubObjects(    
  val exampleString : String = "Example 1",
  val exampleStringTwo : String = "Example 2",
  val exampleStringThree: String = "Example 3"    
  )


data class ProfileEntity(
    @PrimaryKey(autoGenerate = true) val id: Long?,
    @ColumnInfo(name = "profile") var profille: Profile
) : Parcelable

如何在房间数据库中保存 Profile 对象?我被困在这个对象的类型转换器上。

【问题讨论】:

  • 使用GSON库将对象转换为JSONString

标签: android kotlin android-room typeconverter


【解决方案1】:

使用TypeConverter

类型转换器实际上是用于转换简单类型,比如日期或枚举值,但是它可以用于这种情况。您需要有某种方法将您的SubObject 转换为String,可能带有某种您确信在您的对象字段中不存在的定界符。所以像:

fun SubObject.toString() = "$exampleString@@$exampleString2@@$exampleString3"

但这并没有真正利用 SQL 的用途,即基于列的数据。

使用关系

这可能是您想要的方法。通过为您的ProfileSubObject 模型设置一个单独的Entity,然后您可以查询数据库以返回您的ProfileSubObject 之间的关系,特别是在一对多关系中。在 Room 中,这是使用 @Embedded@Relation 注释实现的。我建议您查看 Android Devleopers 文档here,但对于您的示例,您需要这样的内容:

class ResolvedProfile(
    @Embedded
    val profile: Profile,
    @Relation(parentColumn = "profileId", entityColumn = "subObjectProfileId")
    val subObjects: List<SubObject>
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-22
    • 2023-01-21
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2020-07-21
    相关资源
    最近更新 更多