首页 > 解决方案 > 如何正确构建具有继承的房间实体

问题描述

我有一个我希望每个实体都拥有的字段列表,因此我创建了一个基本实体。

open class Syncable(
    @ColumnInfo(name = "id")
    var oid: String? = null,
    @ColumnInfo(name = "created")
    var created: Long = System.currentTimeMillis(),
    @ColumnInfo(name = "updated")
    var updated: Long = System.currentTimeMillis())

然后我有许多从这个继承的实体,例如:

@Entity(tableName = ProfileContract.TABLE_NAME, indices = [Index(value = ["id"], unique = true)])
data class Profile(ColumnInfo(name = "first_name")
     var firstName: String,
     @ColumnInfo(name = "last_name")
     var lastName: String,          
     @ColumnInfo(name = "email")
     var email: String? = null,
     @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "row_id")
     var id: Long? = null) : Syncable()

现在,当我想构建这些实体之一时。我该怎么做?

目前我做:

val newProfile = Profile(
                    "Bob",
                    "Shoruncle",
                    "bobshoruncle@test.com)
newProfile.id = "bob1"
newProfile.created = 1233L
newProfile.updated = 1233L

有没有办法做到这一点:

val newProfile = Profile("Bob", "Shoruncle", "bobshoruncle@test.com","bob1",1233L,1233L)

标签: androidinheritancekotlinconstructorandroid-room

解决方案


@a_local_nobody 是在正确的轨道上,但答案更复杂。

我需要在子类上创建一个自定义构造函数来设置父类的字段

 @Entity(tableName = ProfileContract.TABLE_NAME, indices = [Index(value = ["id"], unique = true)])
 data class Profile(ColumnInfo(name = "first_name")
 var firstName: String,
 @ColumnInfo(name = "last_name")
 var lastName: String,          
 @ColumnInfo(name = "email")
 var email: String? = null,
 @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "row_id")
 var id: Long? = null) : Syncable() {
 @Ignore constructor(
   firstName: String,
   lastName: String,
   email: String,
   id: String,
   created: Long,
   updated:Long) : this(firstName, lastName, email) {
     this.id = id
     this.created = created
     this.updated = updated
   }
 }

现在对于外部创作者来说,它看起来像是一个大的构造函数


推荐阅读