You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Room中autoGenerate=false时插入数据如何获取返回值?

手动设置String类型主键时Room插入操作的返回值处理

Room 在手动指定主键(autoGenerate=false)的场景下,@Insert 注解的方法可以返回 Int 类型值,以此判断插入是否成功:

  • 插入成功(无冲突)时返回 1(代表插入的行数)
  • 因冲突触发 OnConflictStrategy.IGNORE 导致插入失败时返回 0

你只需要修改 Dao 中的方法签名,让它返回 Int 即可:

修改后的 UserDao

@Dao
interface UserDao {
    @Insert(onConflict = OnConflictStrategy.IGNORE)
    suspend fun createUser(userTable: UserTable): Int // 返回插入行数
}

调用示例(用于更新UI)

在 Repository 或 ViewModel 中调用该方法,根据返回值判断操作结果,进而更新UI状态:

suspend fun addUser(user: UserTable): Boolean {
    val insertResult = userDao.createUser(user)
    return insertResult == 1 // 返回true表示插入成功,可据此更新UI
}

补充说明

当 autoGenerate=true 时,Room 返回自动生成的 Long 型主键,是因为此时主键由Room生成,需要返回给调用者;而手动指定主键时,主键值已由你传入,Room 只需告知插入是否成功,返回行数就足够判断状态。

内容的提问来源于stack exchange,提问作者kallis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 11:34:57