我是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似乎以某种方式创建了两个具有相同名称的列(对于父类和子类),我尝试在BaseModel类内的每个字段上方添加@Ignore
批注。它解决了问题,项目成功构建,但是我不确定这是最好的方法。
关于android - 如何实现Room实体的继承(Android,Kotlin),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63379866/