房间错误:参数的类型必须是带有@Entity或其集合/数组的类

时间:2019-08-25 07:49:42

标签: android kotlin android-room

我遇到以下错误:

error: Type of the parameter must be a class annotated with @Entity or a collection/array of it.
    java.lang.String matchId);

在我的matchedBefore()查询中:

@Dao
interface MatchedUsersDao {

    // Checks to see if user has matched before (if it returns 1)
    @Query("SELECT COUNT(*) FROM matched_users WHERE :matchId = match_id LIMIT 1")
    fun matchedBefore(matchId: String): Int

    @Insert(onConflict = OnConflictStrategy.ABORT)
    fun addMatchUid(matchId: String)
}

这是我的实体

@Entity(tableName = "matched_users")
data class MatchedUser(
    @PrimaryKey(autoGenerate = true) val id: Int,
    @ColumnInfo(name = "match_id") val matchId: String
)

数据库

@Database(entities = arrayOf(MatchedUser::class), version = 1)
abstract class AppDatabase : RoomDatabase() {

    abstract fun matchedUsersDao(): MatchedUsersDao
}

然后我在应用程序中实例化数据库:

class CustomApplication : Application() {

    companion object {
        var database: AppDatabase? = null
    }

    override fun onCreate() {
        super.onCreate()
        CustomApplication.database = Room.databaseBuilder(this, AppDatabase::class.java, "AppDatabase").build()
    }

有人可以告诉我该错误指示什么以及如何解决吗?

1 个答案:

答案 0 :(得分:4)

您的问题是这行

@Insert(onConflict = OnConflictStrategy.ABORT)
fun addMatchUid(matchId: String)

如果要使用@Insert批注,则必须发送MatchedUser而不是String的实例。

因此您可以:

1)发送具有您的ID的新MatchedUser(插入具有您的ID的空MatchedUser

您的代码必须是这样

@Insert(onConflict = OnConflictStrategy.ABORT)
fun addMatchUid(matchUser: MatchedUser)

2)编写了新的@Query以便仅在数据库中插入ID