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

既然無法直接存儲,那有其他辦法解決嗎?當然有了,利用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() {
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章