Room:使用@Transaction时收到错误

Mar*_*arr 15 android kotlin android-room

我的DAO类中有一个使用@Transaction注释的方法,这会导致以下错误:

DAO方法只能使用以下方法之一进行注释:插入,删除,查询,更新

这是我的班级:

@Dao interface Dao {

    @Insert(onConflict = REPLACE) fun insertList(chacaras: List<String>)

    @Query("SELECT * FROM chacara WHERE cityId = :cityId")
    fun getListOfCity(cityId: String): LiveData<List<String>>

    @Delete fun deleteList(chacaraList: List<String>)

    @Transaction
    fun updateList(list: List<String>){
        deleteList(list)
        insertList(list)
    }

}
Run Code Online (Sandbox Code Playgroud)

当我删除使用@Transaction注释的方法时,它会正常编译.有没有什么办法解决这一问题?

Mar*_*arr 28

根据交易文件

抽象Dao类中的方法标记为事务方法.

将您的班级更改为:

@Dao abstract class Dao {

    @Insert(onConflict = REPLACE) abstract fun insertList(chacaras: List<String>)

    @Query("SELECT * FROM chacara WHERE cityId = :cityId")
    abstract fun getListOfCity(cityId: String): LiveData<List<String>>

    @Delete abstract fun deleteList(chacaraList: List<String>)

    @Transaction
    open fun updateList(list: List<String>){
        deleteList(list)
        insertList(list)
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 对我来说,关键是使用open方法,因为我已经有了一个抽象类。 (5认同)