ROOM无法弄清楚如何将该字段保存到数据库中 [英] ROOM Cannot figure out how to save this field into database
问题描述
我需要你的帮助. 我尝试在不进行反序列化的情况下找到解决方案,但没有发现任何问题. 如果您能帮助我,那就太好了... 所以我有这个以下JSON文件
I need your help. I try to find the solution without deserialize but I didn't find nothing. It would be nice if you can help me... So I have this following JSON file
"resources": [{
"id": 441988,
"name": "TVA",
"parent": {
"id": 159
},
},
{
"id": 441900,
"name": "Marketing",
"parent": {
"id": 166
},
}]
我用ROOM创建了一个数据库,它可以工作,但是我有一个问题, 无法保存父对象的ID"
I used ROOM to create a database, it works but I have one problem, its impossible to save "id of Parent object"
这是我的以下代码:
@Entity(tableName = "resources")
class CategoryBean {
@PrimaryKey
@ColumnInfo(name = "resource_id")
@SerializedName("id")
private var mId: Int = 0
@ColumnInfo(name = "name")
@SerializedName("name")
private var mName: String? = null
@ColumnInfo(name = "parent")
@SerializedName("parent")
private var mParent: ParentBean? = null
fun getId(): Int {
return mId
}
fun getName(): String? {
return mName
}
fun getParent(): ParentBean? {
return mParent
}
fun setParent(parent: ParentBean) {
mParent = parent
}
fun setId(id: Int) {
mId = id
}
fun setName(name: String) {
mName = name
}
在这里您可以找到我的ParentBean文件
Here you can find my ParentBean file
class ParentBean {
@SerializedName("id")
private var mId: Int = 0
fun getId(): Int? {
return mId
}
}
我找到了一些列表的解决方案,但没有找到子对象的解决方案.
I found some solution for a list, but not for sub object.
感谢您的时间和帮助.
有我以下错误:
Cannot figure out how to save this field into database. You can consider adding a type converter for it.
推荐答案
Room在SQLite数据库上运行,当您将类注释为@Entity
时,您正在创建一个表,该表的列根据类,因此您不能直接存储ParentBean
之类的自定义类型,为此,您需要将mParent
属性注释为@Embedded
:
Room works on top of a SQLite database, when you annotate a class as @Entity
you are creating a table whose columns are defined according to the properties of the class, so you can't store directly a custom type like ParentBean
, to do that, you need to annotate mParent
property as @Embedded
:
@Entity(tableName = "resources")
class CategoryBean constructor(
@PrimaryKey
@ColumnInfo(name = "resource_id")
@SerializedName("id")
var mId: Int,
@ColumnInfo(name = "name")
@SerializedName("name")
var mName: String?,
@SerializedName("parent")
@Embedded
var mParent: ParentBean?
)
然后在ParentBean
中为属性定义列名:
Then you define a column name for the property in ParentBean
:
data class ParentBean constructor(@SerializedName("id") @ColumnInfo(name = "parent_id")var mId: Int)
资源表将包含以下列:resource_id
,name
,parent_id
resources table will have the following columns: resource_id
, name
, parent_id
来源: https://developer.android.com/training/data-storage/room/defining-data
注意:您无需在Kotlin中手动定义getter和setter.
Note: You don't need to manually define getter and setters in Kotlin.
这篇关于ROOM无法弄清楚如何将该字段保存到数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!