问题
I'm currently learning about the Room Persistence and I just want to ask on how to create a TypeConverter for a custom class?
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
Right now I'm encountering an error and it says,
error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.
and pointing to my Product
class
I tried to put an annotation to my Product
class like @TypeConverters(Brand.class)
and still the error is popping, I really don't know what to do.
Any help is appreciated, Thanks.
回答1:
You can use @Embedded
instead.
@Embedded
val brand: Brand,
From 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.
来源:https://stackoverflow.com/questions/58296346/android-room-how-to-add-a-typeconverter