我目前正在学习 Room Persistence,我只是想问一下如何为自定义类创建 TypeConverter?
Brand.kt
@Parcelize
@Entity(tableName = "brand")
data class Brand (
@PrimaryKey(autoGenerate = false)
@ColumnInfo(name = "id")
val id: Int,
@ColumnInfo(name = "name")
val name: String
) : Parcelable
产品.kt
@Parcelize
@Entity(tableName = "product")
data class Product(
@PrimaryKey(autoGenerate = false)
@ColumnInfo(name = "id")
val id: Int,
@ColumnInfo(name = "brand")
val brand: Brand, // This variable is my problem, I don't know how to fix it...
@ColumnInfo(name = "name")
val name: String,
@ColumnInfo(name = "price")
val price: Int
) : Parcelable
现在我遇到一个错误,它显示:
error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.
并指向我的Product
类
我尝试将注释添加到我的 Product
类中,例如 @TypeConverters(Brand.class)
,但仍然弹出错误,我真的不知道该怎么办做。
感谢任何帮助,谢谢。
最佳答案
您可以使用@Embedded
来代替。
@Embedded
val brand: Brand,
来自docs:-
Can be used as an annotation on a field of an Entity or Pojo to signal that nested fields (i.e. fields of the annotated field's class) can be referenced directly in the SQL queries.
关于Android Room - 如何添加类型转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58296346/