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

使用Room的@Upsert注解时出现唯一约束异常该如何解决?

关于Room @Upsert注解触发SQLite唯一约束异常的问题及临时处理

使用Room的@Upsert注解实现数据保存功能时,触发SQLite唯一约束异常,报错信息如下:

android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: characters.uuid (code 2067 SQLITE_CONSTRAINT_UNIQUE)
    at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
    at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:938)
    at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:790)
    at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:88)
    at androidx.sqlite.db.framework.FrameworkSQLiteStatement.executeInsert(FrameworkSQLiteStatement.kt:42)
    at androidx.room.EntityInsertionAdapter.insert(EntityInsertionAdapter.kt:52)
    at androidx.room.EntityUpsertionAdapter.upsert(EntityUpsertionAdapter.kt:59)
    at com.instance.dataxbranch.data.daos.UserDao_Impl.save(UserDao_Impl.java:1409)
    at com.instance.dataxbranch.data.repository.GeneralRepository$save$2.invokeSuspend(GeneralRepository.kt:171)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    at kotlinx.coroutines.internal.LimitedDispatcher.run(LimitedDispatcher.kt:42)
    at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:95)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:570)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:677)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:664)
    Suppressed: kotlinx.coroutines.DiagnosticCoroutineContextException: [StandaloneCoroutine{Cancelling}@d25d977, Dispatchers.IO]

UserDao中的代码:

@Upsert
abstract fun save(char: CharacterEntity)

后续修改了GeneralRepository中的save方法,添加异常捕获与日志打印:

fun save(char: CharacterWithStuff=selectedCharacterWithStuff):Job =
        CoroutineScope(Dispatchers.IO).launch {
            try {
                uDao.save(char.character)
            }catch (e: Exception){
                Log.d(TAG,"GOTCHA BISH $e")
            }
            updateByCharacterList(char)
            needsSync=true
        }

添加异常捕获后程序不再崩溃,Upsert功能似乎恢复正常,后续若有问题会补充说明。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 10:15:34