如果在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() {}
来源:
互联网
本文观点不代表码客-全球程序员交流社区立场,不承担法律责任,文章及观点也不构成任何投资意见。
评论列表