在Room数据库中如何存储BigDecimal数据

如果在Room数据库中直接存储BigDecimal是无法存储的,Date类型的数据同样如此,会报以下错误

@Entity(foreignKeys = [ForeignKey(entity = RecordType::class, parentColumns = ["id"], childColumns = ["record_type_id"])], indices = [Index(value = ["record_type_id", "time", "money", "create_time"])])
open class Record : Serializable {
    @PrimaryKey(autoGenerate = true)
    var id = 0
    var money: BigDecimal? = null
    var remark: String? = null
    var time: Date? = null

    @ColumnInfo(name = "create_time")
    var createTime: Date? = null

    @ColumnInfo(name = "record_type_id")
    var recordTypeId = 0
}

image.png

既然无法直接存储,那有其他办法解决吗?当然有了,利用TypeConverters �|� Android Developers注解就可以处理

解决思路:利用TypeConverters将BigDecimal转换为Long数据存储,取数据时再将Long类型的数据转换为BigDecimal使用

1.在room中,我们主要可以通过@TypeCoventer注解来实现一个类型转换器。

object Converters {
    @TypeConverter
    fun fromTimestamp(value: Long?): Date? {
        return if (value == null) null else Date(value)
    }

    @TypeConverter
    fun dateToTimestamp(date: Date?): Long? {
        return date?.time
    }

    @TypeConverter
    fun stringToBig(intDecimal: Int): BigDecimal {
        return BigDecimal(intDecimal)
    }

    @TypeConverter
    fun bigToString(bigDecimal: BigDecimal): Int {
        return bigDecimal.toInt()
    }
}

2.在实现类型转换器之后,在表中引入这个转换器即可,也可以直接加在RoomDatabase这个类上,不用每个实体类都加一次,这样就可以实现自动转换了

@Database(entities = [Inspiration::class, Daiban::class, SportClass::class, SportLog::class, Record::class, RecordType::class], version = 4, autoMigrations = [
    AutoMigration(from = 1, to = 2),
    AutoMigration(from = 2, to = 3),
    AutoMigration(from = 3, to = 4),
])
@TypeConverters(Converters::class)
abstract class AppDataBase : RoomDatabase() {
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容