【问题标题】:Room: Receiving error when using @TransactionRoom:使用@Transaction 时收到错误
【发布时间】:2018-03-25 14:31:25
【问题描述】:

我的 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)
    }

}

当我删除带有 @Transaction 注释的方法时,它会正常编译。 有没有办法解决这个问题?

【问题讨论】:

    标签: android kotlin android-room


    【解决方案1】:

    根据transaction documentation

    抽象道类中的方法标记为事务方法。

    将您的班级更改为:

    @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)
        }
    
    }
    

    【讨论】:

    • 不应该@Query也用Transaction注释吗?
    • 对我来说关键是使用open 作为方法,因为我已经有了一个抽象类。
    • @FirstOne 完全正确。除非您明确将它们定义为“开放”方法,否则方法在 kotlin 中被视为“最终”方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-07
    • 1970-01-01
    相关资源
    最近更新 更多