android - 如何正确构建具有继承的房间实体
问题描述
我有一个我希望每个实体都拥有的字段列表,因此我创建了一个基本实体。
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)
解决方案
@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
}
}
现在对于外部创作者来说,它看起来像是一个大的构造函数
推荐阅读
- linux - Gitlab CI:docker中的服务器正在询问我的SSH密钥密码,即使它没有
- excel - 如何将不相邻的列复制到另一个 Excel 工作簿?
- erlang - 借助 Erlang 在 CouchDB 中创建视图
- sql - sql查询以支付方式的条件进行销售总和
- c# - IEnumerable.ElementAt - 值存在时参数超出范围异常
- excel - 如何计算非静态数据透视表上最大/最小日期之间的差异?
- docker - 使用命令启动或运行 docker 容器
- django - serializer_class django todo 应用程序上的断言错误
- c - 了解 Tokyo Cabinet 中的 tchdbfwmkeys 方法(获取数据库中的前向匹配键)
- c++ - 如何实现 If-Else 条件模板?