Android Room - 如何添加类型转换器

标签 android android-room

我目前正在学习 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/

相关文章:

android - 我在尝试使用 Room 数据库时收到此错误消息

android - 连接 ROOM 数据库中的表

android - 从 Activity 的 onCreate 访问 Fragment View

android - 使用tomtom location api android获取用户之间的距离

android - Jetpack 撰写 : calling action inside LauchedEffect blocks UI anyway

android - Room - 模式导出目录未提供给注释处理器,因此我们无法导入模式

android - 修改从 Room 获取的 LiveData 项目

java - 使用电话号码比较查询数据库

android - 移动支付库转账问题

java - Android 使用 OpenGL-ES 中的 glBlendFunc 混合获得正确的不透明度/颜色