汽车行业
在Room数据库中如何存储BigDecimal数据
2022-12-08 20:31  浏览:206

如果在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}

既然无法直接存储,那有其他办法解决么?当然有了,利用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() {}