为什么 Room 实体不能使用 Android 中的不可变属性
Why Room entities don't work with immutable properties in Android
我一直在探索 Room 数据库对象映射库,我发现了一些奇怪的东西。
实体数据模型不能具有不可变的属性,如 答案所建议的那样。
但我从示例中检查了 google's persistent example with kotlin, Room
works with immutable properties too. Please check this 数据 class。
这种行为的原因可能是什么?
如果我们可以创建不可变值(val
属性),这可能是一个很好的功能,因为这会限制程序员在创建对象后更改唯一标识符,例如 id。
这很奇怪,因为我可以在我的所有字段中使用 val
使我的实体 class 没有问题
@Entity(tableName = "repo")
data class RepoEntity(
@PrimaryKey @ColumnInfo(name = "id") @SerializedName("id") val id: Int,
@ColumnInfo(name = "name") @SerializedName("name") val name: String,
@ColumnInfo(name = "full_name") @SerializedName("full_name") val fullName: String,
@Embedded(prefix = "owner") @SerializedName("owner") val owner: RepoOwnerEntity,
@ColumnInfo(name = "html_url") @SerializedName("html_url") val htmlUrl: String,
@ColumnInfo(name = "description") @SerializedName("description") val description: String?
)
而且数据仍然正确地存储在数据库中。
我认为问题源于某些不能作为构造函数参数的字段。来自 @Relation
注释的 Javadoc:
Note that the @Relation
annotated field cannot be a constructor parameter, it must be public or have a public setter.
作为解决方法,我有一个私有构造函数参数 _myRelationProperty
和一个 public 字段:
val myRelationProperty: List<MyThings> get() = _myRelationProperty
我一直在探索 Room 数据库对象映射库,我发现了一些奇怪的东西。
实体数据模型不能具有不可变的属性,如
但我从示例中检查了 google's persistent example with kotlin, Room
works with immutable properties too. Please check this 数据 class。
这种行为的原因可能是什么?
如果我们可以创建不可变值(val
属性),这可能是一个很好的功能,因为这会限制程序员在创建对象后更改唯一标识符,例如 id。
这很奇怪,因为我可以在我的所有字段中使用 val
使我的实体 class 没有问题
@Entity(tableName = "repo")
data class RepoEntity(
@PrimaryKey @ColumnInfo(name = "id") @SerializedName("id") val id: Int,
@ColumnInfo(name = "name") @SerializedName("name") val name: String,
@ColumnInfo(name = "full_name") @SerializedName("full_name") val fullName: String,
@Embedded(prefix = "owner") @SerializedName("owner") val owner: RepoOwnerEntity,
@ColumnInfo(name = "html_url") @SerializedName("html_url") val htmlUrl: String,
@ColumnInfo(name = "description") @SerializedName("description") val description: String?
)
而且数据仍然正确地存储在数据库中。
我认为问题源于某些不能作为构造函数参数的字段。来自 @Relation
注释的 Javadoc:
Note that the
@Relation
annotated field cannot be a constructor parameter, it must be public or have a public setter.
作为解决方法,我有一个私有构造函数参数 _myRelationProperty
和一个 public 字段:
val myRelationProperty: List<MyThings> get() = _myRelationProperty