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

Room框架下@PrimaryKey(autoGenerate=true)插入ID恒为0的解决方法

Android Room 主键自动生成失效,ID始终为0的解决方法

问题重现

使用Room框架时,实体类中已设置@PrimaryKey(autoGenerate = true),但插入数据时所有记录的ID始终为0,无法自动递增。相关代码如下:

实体类代码

@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "exploitsId")
var id: Long = 0
var name: String? = null


constructor(id: Long, name: String) {
    this.id = id
    this.name = name
}

constructor(name: String) {
    //this.id = null
    this.name = name
}

Dao层代码

@Dao
interface daoExploits {
@Query("SELECT * FROM exploitsEntTable")
fun getAllexploits(): LiveData<List<exploitsEnt>>


@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertExploit(ExploitsEnt: exploitsEnt)
}

ViewModel层代码

fun insertExploit(ExploitsEnt: exploitsEnt) {
    repository.insertExploit(ExploitsEnt)
}

调用viewModel.insertTest(exploitsEnt("hello"))插入多条重复数据时,所有数据的ID始终保持为0。

原因分析

Room的autoGenerate = true触发自动主键生成的前提是主键字段值为null。当把id的默认值设为0时,Room会将其视为一个有效的主键值,不会执行自动生成逻辑。再结合Dao中使用的OnConflictStrategy.REPLACE策略,每次插入ID为0的数据时都会覆盖之前同ID的记录,最终导致所有插入的"hello"数据ID均为0。

解决方法

将实体类中的id字段改为可空类型,默认值设为null:

@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "exploitsId")
var id: Long? = null

修改后,调用仅传入name的构造函数时,id为null,Room会自动生成递增的主键ID,不会再出现所有数据ID为0的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 20:32:35