首页 > 解决方案 > 如何将房间中的对象保存在数据库中。Kotlin 安卓

问题描述

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

我要保存在数据库中的配置文件对象类:

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 对象保存在房间数据库中?我被困在这个对象的类型转换器上。

标签: androidkotlinandroid-roomtypeconverter

解决方案


用一个TypeConverter

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

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

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

使用关系

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

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

推荐阅读