android - 如何将房间中的对象保存在数据库中。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 对象保存在房间数据库中?我被困在这个对象的类型转换器上。
解决方案
用一个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>
)
推荐阅读
- r - str_replace_all 不适用于包含括号的字符串
- spring-boot - 使用 Vault Agent Sidecar 配置 Spring Vault
- regex - 正则表达式 - 匹配来自任何语言的所有字符和所有正时字符,除了
- java - JavaFX - 单击按钮时尝试弹出一个屏幕
- r - 如何在 r-markdown pdf 中将数据框类别描述为部分和内容?
- google-apps-script - 无法将 JSON 数据的值设置为分隔单元格
- python - 如何通过 git-python 添加/提交和推送存储库?
- iis - IIS 是否记录 web.config 更改?即使我直接编辑了文件?
- python-3.x - Python重复了ThreadPoolExecutor的某些任务
- c# - 如何修复 CrystalDecisions.CrystalReports.Engine.ReportDocument' 引发异常