我正在嘗試向我的表添加新屬性,如下所示:
@Entity(
tableName = "invoices", indices = [Index(value = [...], unique = true)]
)
data class Invoice(
...
override val created_at: Long = 0,
override var approved_at: Long? = 0,
) : ICD
所以我創建了以下遷移:
val MIGRATION_3_4 = object: Migration(3, 4) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE invoices ADD COLUMN created_at INTEGER NOT NULL DEFAULT 0")
database.execSQL("ALTER TABLE invoices ADD COLUMN approved_at INTEGER DEFAULT 0 ")
}
}
但是每當我嘗試運行時,它都會說遷移沒有得到正確處理并按預期顯示:
TableInfo{name='invoices', columns={... ,created_at=Column{name='created_at', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'}, approved_at=Column{name='approved_at', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0, defaultValue='null'}}, ... }
這是什么發現:
TableInfo{name='invoices', columns={... ,created_at=Column{name='created_at', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='0'}, approved_at=Column{name='approved_at', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0, defaultValue='0'}}, ... }
誰能告訴我為什么它期待默認值 null 請?
uj5u.com熱心網友回復:
我相信,您使用的 Room 版本大于2.2.0,并且版本2.2.0和更高版本需要使用在各自物體類中定義的列的默認值@ColumnInfo(defaultValue="0")
對于您的情況,添加@ColumnInfo(defaultValue="0")到created_at和approved_at
@ColumnInfo(defaultValue="0")
override val created_at: Long = 0,
@ColumnInfo(defaultValue="0")
override var approved_at: Long? = 0,
并將您的遷移功能更改為此
database.execSQL("ALTER TABLE invoices ADD COLUMN created_at INTEGER NOT NULL DEFAULT 0")
database.execSQL("ALTER TABLE invoices ADD COLUMN approved_at INTEGER")
如果您使用的是 Room 版本2.4.0-alpha01及更高版本,則可以使用autoMigration.
對于autoMigration,autoMigrations向資料庫添加注釋
@Database(
entities = [.., .., ..],
version = 2,
autoMigrations = [AutoMigration(from = 1, to = 2)]
)
abastract class Database: RoomDatabase
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/325077.html
標籤:安卓 sqlite 科特林 android-room
