Room 数据库自增长id导致数据插入失败的解决方案

问题描述

    在Room数据库中,我们定义数据实体类跟数据库表进行一一对应,在定义的表时我们经常会用到自增长的id列,定义了自增长的列,在插入数据时构建数据实体对象时,如果数据实体类中使用了自增长的id列,数据插入时id列的值可以设置为 null (Kotlin,Java中使用默认值),数据库会自动编排id值。但是如果数据实体类中的id列指定了默认值,出现了数据无法插入的问题(笔者经历)。如下代码所示:

// 数据实体定义
@Entity(tableName = "records")
class Record(@ColumnInfo var timeMillisecond: Long, @ColumnInfo var date: String, @ColumnInfo var time: String,
             @ColumnInfo var dateYM: String, @ColumnInfo var chargeAmount: Float, @ColumnInfo var chargeCost: Float,
             @ColumnInfo var mileage: Int, @ColumnInfo var socBefore: Int = 0, @ColumnInfo var socAfter: Int = 0,
             @ColumnInfo var station: String? = null, @ColumnInfo var memo: String? = null,
             @ColumnInfo var extra: String? = null, @ColumnInfo var carId: Long = -1) {
    @PrimaryKey(autoGenerate = true) var id: Long = -1
}

在其自编id时,以上定义的数据实体无法插入数据。

问题定位

    根据前面提到,问题就出在指定了id列的默认值,导致数据库插入数据时无法编排id导致插入数据失败,但是并不是不能指定默认值,笔者遇到这个问题最终发现是id列的默认值不能为负数。

解决方案

    如果用Java语言,直接使用默认值即可,或者指定0位id列的默认值。如果使用 Kotlin 语言开发,可将 id 列定义为可空,或者指定默认值为 0.

// 数据实体定义
@Entity(tableName = "records")
class Record(@ColumnInfo var timeMillisecond: Long, @ColumnInfo var date: String, @ColumnInfo var time: String,
             @ColumnInfo var dateYM: String, @ColumnInfo var chargeAmount: Float, @ColumnInfo var chargeCost: Float,
             @ColumnInfo var mileage: Int, @ColumnInfo var socBefore: Int = 0, @ColumnInfo var socAfter: Int = 0,
             @ColumnInfo var station: String? = null, @ColumnInfo var memo: String? = null,
             @ColumnInfo var extra: String? = null, @ColumnInfo var carId: Long = -1) {
    @PrimaryKey(autoGenerate = true) var id: Long = -1
}

// 数据实体定义2
@Entity(tableName = "records")
class Record(@ColumnInfo var timeMillisecond: Long, @ColumnInfo var date: String, @ColumnInfo var time: String,
             @ColumnInfo var dateYM: String, @ColumnInfo var chargeAmount: Float, @ColumnInfo var chargeCost: Float,
             @ColumnInfo var mileage: Int, @ColumnInfo var socBefore: Int = 0, @ColumnInfo var socAfter: Int = 0,
             @ColumnInfo var station: String? = null, @ColumnInfo var memo: String? = null,
             @ColumnInfo var extra: String? = null, @ColumnInfo var carId: Long = -1) {
    @PrimaryKey(autoGenerate = true) var id: Long? = null
}

你可能感兴趣的:(#,使用,Room,管理数据库,kotlin,java,android)