gpt4 book ai didi

android - 如何实现 Room 实体的继承(Android、Kotlin)

转载 作者:行者123 更新时间:2023-12-02 13:41:05 28 4
gpt4 key购买 nike

我是 Room 新手,没有找到任何与此相关的帖子。
我有两个类:BaseModel 和 ChildModel。 ChildModel 是 Room 实体类,但 BaseModel - 不是。如何正确从 ChildModel 扩展 BaseModel?我试着按照下面的代码来做......
BaseModel.kt:

@Parcelize
open class BaseModel(
open val id: String,
open var name: String,
open var creator: String,
open var dateOfLastEdit: Timestamp,
open var contributors: List<String>,
open var color: Int,
open var offline: Boolean
) : Parcelable {...}
ChildModel.kt (用于 firebase 的空构造函数):
@Entity
@Parcelize
data class ChildModel(
@PrimaryKey(autoGenerate = false)
override val id: String = "",
override var name: String = "",
override var creator: String = "",
@TypeConverters(DateTypeConverter::class)
override var dateOfLastEdit: Timestamp = currentTime(),
@TypeConverters(ListStringConverter::class)
override var contributors: List<String> = emptyList(),
override var color: Int = NO_COLOR,
override var offline: Boolean = false,
var text: String = "",
var lastEditTextPosition: Int = 0,
var lastEditNamePosition: Int = 0,
var lastUserEdited: String = ""
) : Parcelable, BaseModel(id, name, creator, dateOfLastEdit, contributors, color, offline) {
constructor() : this("", "", "", currentTime(), emptyList(), NO_COLOR, false, "", 0, 0, "")
...
}
...但它给出了错误: “字段具有非唯一的列名”对于从 BaseModel 覆盖的所有字段。顺便说一句,当创建 BaseModel 作为接口(interface)时,它会成功构建。
我的数据库类:
@Database(entities = [ChildModel::class], version = 1)
@TypeConverters(DateTypeConverter::class, ListStringConverter::class)
abstract class CustomDatabase : RoomDatabase() {
abstract fun childModelDao(): ChildModelDao

companion object {
var INSTANCE: CustomDatabase? = null

fun getDatabase(context: Context): CustomDatabase? {
if (INSTANCE == null) {
synchronized(CustomDatabase::class) {
INSTANCE = Room.databaseBuilder(
context.applicationContext,
CustomDatabse::class.java,
DATABASE
).build()
}
}
return INSTANCE
}
fun destroyDatabase() {
INSTANCE = null
}
}
}
该错误与升级数据库版本无关,因为我删除了上一个。
提前致谢!

最佳答案

好的,似乎 Room 以某种方式创建了两个具有相同名称的列(对于父类和对于子类)我尝试添加 @Ignore BaseModel 类中每个字段上方的注释。它解决了问题,项目成功构建,但我不确定这是最好的方法。

关于android - 如何实现 Room 实体的继承(Android、Kotlin),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63379866/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com