为房间中的其他DTO添加迁移



我有DTO:

@Entity(tableName = "product")
data class ProductDTO(
@Embedded
val attributes: AttributesDTO,
val autocomplete: String,
val basePhoto: String,
val baseColors: BaseColors) {

}

和属性DTO

@Entity(tableName = "attributes")
class AttributesDTO {
@PrimaryKey
var attributeId: Long = 0
var battery: String = ""
var brand: String = ""
constructor(battery: String, brand: String) {
this.battery = battery
this.brand = brand
}
}

我想添加新的字段PriceAttributeDTO,并需要为此创建迁移。在数据库预览中,我可以看到AttributeDTO中的所有字段都可以在ProductDTO表中使用。我该怎么做呢?房间版本:2.2.5.

通过以下文档:

首先将你的属性添加到你的类中:

@Entity(tableName = "attributes")
class AttributesDTO {
@PrimaryKey
var attributeId: Long = 0
var battery: String = ""
var brand: String = ""
var price: Int?
constructor(battery: String, brand: String) {
this.battery = battery
this.brand = brand
}
}

您可以添加自动迁移或手动迁移:

自动迁移:

请添加以下注释:

@Database(
version = 2,
entities = [AttributeDTO::class],
autoMigrations = [
AutoMigration (from = 1, to = 2)
]
)
abstract class AppDatabase : RoomDatabase() {
...
}

手动迁移:

val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE attributes ADD COLUMN price INTEGER")
}
}

当你创建你的房间数据库时,添加它:

Room.databaseBuilder(appContext, AppDatabase.class, "Sample.db")
.addMigrations(MIGRATION_1_2)
.build()

最新更新