kotlin 为什么我不能在dao的@Insert in room数据库中使用suspend修饰符?

46qrfjad  于 2022-12-23  发布在  Kotlin
关注(0)|答案(2)|浏览(206)

当我在DAO中使用@Insert函数时,出现以下错误。

error: Type of the parameter must be a class annotated with @Entity or a collection/array of it.

所有其他使用Room use的代码都在@Insert中挂起,所以我不知道错误的原因。
然后我只是删除了挂起,它工作正常。
为了什么原因?

    • 分级**
def room_version = "2.4.2"

implementation "androidx.room:room-runtime:$room_version"
implementation "androidx.room:room-ktx:$room_version"
kapt "androidx.room:room-compiler:$room_version"
    • 实体**
@Entity
data class DailyWorkout(
    @PrimaryKey(autoGenerate = true)
    val id : Int = 0,
    val date: String,
    val bodyPart: String, // bodyPart
)
    • DAO**
@Dao
interface WorkoutDao {
    @Query("SELECT * From WorkoutList")
    fun getWorkoutList() : List<WorkoutList>

    @Insert
    fun insertDailyLog(dailyWorkout: DailyWorkout)
}
    • 存储库**
class WorkoutListRepository(private val dao: WorkoutDao) {

    @RequiresApi(Build.VERSION_CODES.O)
    fun createDailyLog(part: BodyPart) {
        val date = LocalDate.now()
        val formatter =
            DateTimeFormatter
                .ofPattern("yyyy/M/dd E")
                .format(date)

        val data = DailyWorkout(date = formatter, bodyPart = part.getPart())
        dao.insertDailyLog(data)
    }
}
    • 视图模型**
class WorkoutListViewModel(
    private val repository: WorkoutListRepository

) : ViewModel() {
    private var _list = MutableLiveData<List<String>>()
    val list: LiveData<List<String>>
        get() = _list

    @RequiresApi(Build.VERSION_CODES.O)
    fun createDailyLog(part: BodyPart) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.createDailyLog(part)
        }
    }
}
20jt8wwn

20jt8wwn1#

尝试更新gradle依赖关系:

implementation "androidx.room:room-runtime:2.5.0-alpha02"
implementation "androidx.room:room-ktx:2.5.0-alpha02"
kapt "androidx.room:room-compiler:2.5.0-alpha02"
ktca8awb

ktca8awb2#

尝试在您的应用级别build.gradle中将您的聊天室依赖项更新为:

plugins {
    id 'kotlin-kapt'
}

dependencies {

    implementation("androidx.room:room-runtime:2.4.3")
    annotationProcessor("androidx.room:room-compiler:2.4.3")

    kapt("androidx.room:room-compiler:2.4.3")

    implementation("androidx.room:room-ktx:2.4.3")

}

然后可以在DAO中使用suspend修饰符

@Dao
interface WorkoutDao {
    @Query("SELECT * From WorkoutList")
    suspend fun getWorkoutList() : List<WorkoutList>

    @Insert
    suspend fun insertDailyLog(dailyWorkout: DailyWorkout)
}

不要忘记为调用上述suspend函数的函数添加suspend修饰符。在您的情况下,Repository应为

class WorkoutListRepository(private val dao: WorkoutDao) {

    @RequiresApi(Build.VERSION_CODES.O)
    suspend fun createDailyLog(part: BodyPart) {
        val date = LocalDate.now()
        val formatter =
            DateTimeFormatter
                .ofPattern("yyyy/M/dd E")
                .format(date)

        val data = DailyWorkout(date = formatter, bodyPart = part.getPart())
        dao.insertDailyLog(data)
    }
}

有关详细信息:读取this article

相关问题