Room 是否允许非原始数据类型作为主键?

Does Room allow a non-primitive data type as the primary key?

我想使用 Room 编写一个 Kotlin @Entity,并将非原始数据类型作为其 @PrimaryKey。例如:

@Entity
data class MyEntity(
    @PrimaryKey val myType: MyType,
    val text: String
)

我在我的非原始类型 to/from 和字符串之间提供一个 TypeConverter。

class Converters {
    @TypeConverter fun fromString(value: String): MyType = MyTypeUtil.parse(value)
    @TypeConverter fun toString(myType: MyType) = myType.toString()
}

我也在我的数据库中正确注册了我的 TypeConverters:

@Database(
    entities = [
        MyEntity::class
    ],
    version = 1
)
@TypeConverters(
    Converters::class
)
abstract class MyDatabase : RoomDatabase() {

    abstract fun myDao(): MyDao
}

编译失败:

...MyDao_Impl.java: uses unchecked or unsafe operations. Recompile with -Xlint:unchecked for details.

你能帮我找出问题所在吗? Room 是否允许我尝试做的事情?

是 - Room 允许非原始数据类型作为主键。

您的 TypeConverters 中存在错误 - 您必须提供从 StringMyType 以及从 MyTypeString 的转换,因此方法 fromString 必须 return MyType(现在是 returning String)。改变它,它应该工作:)
如果您仍然遇到奇怪的编译错误,请在进行更改后尝试清理项目。