gpt4 book ai didi

Android Room - 如何添加 TypeConverter

转载 作者:行者123 更新时间:2023-12-05 00:20:46 24 4
gpt4 key购买 nike

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

Product.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类(class)

我试图在我的 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 - 如何添加 TypeConverter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58296346/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com