kotlin 如果DAO房间中同时有`@Insert`和`@Upsert`,则编译器失败(Jetpack Compose)

9vw9lbht  于 2023-05-18  发布在  Kotlin
关注(0)|答案(1)|浏览(109)

我有以下代码:

package com.example.secondcompose.dao

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Upsert
import com.example.secondcompose.data.Phone
import kotlinx.coroutines.flow.Flow

@Dao
interface PhoneDao {
    @Insert(onConflict = OnConflictStrategy.NONE)
    suspend fun insertIfMissing(phone: Phone)

    @Upsert
    suspend fun upsert(phone: Phone)

    @Delete
    suspend fun delete(phone: Phone)

    @Query("DELETE FROM phone")
    suspend fun nuke()

    @Query("SELECT * FROM phone WHERE id = :id")
    fun find(id: Long): Flow<Phone?>

    @Query("SELECT * FROM phone ORDER BY manufacturer ASC")
    fun getPhonesOrderedByManufacturer(): Flow<List<Phone>>
}

但是它无法编译:

C:\Users\szmar\AndroidStudioProjects\SecondCompose\app\build\generated\ksp\debug\java\com\example\secondcompose\dao\PhoneDao_Impl.java:160: error: cannot find symbol
          __insertionAdapterOfPhone.upsert(phone);
                                   ^
  symbol:   method upsert(Phone)
  location: variable __insertionAdapterOfPhone of type EntityInsertionAdapter<Phone>

如果我注解掉@InsertinsertIfMissing,它就会编译。为什么?什么是正确的解决办法?

hyrbngr7

hyrbngr71#

onConflict的文档中可以看出,值NONE相当于根本不使用该语句。我建议使用以下方法之一:
使用OnConflictStrategy.ABORT(默认值)在发生冲突时回滚事务。使用OnConflictStrategy.REPLACE将现有行替换为新行。使用OnConflictStrategy.IGNORE保留现有行。

相关问题