Room 2.2.5 为嵌套AttributesDTO新增Price字段的迁移方法咨询
解决步骤
1. 修改AttributesDTO代码新增Price字段
@Entity(tableName = "attributes") class AttributesDTO { @PrimaryKey var attributeId: Long = 0 var battery: String = "" var brand: String = "" // 新增Price字段,可根据业务需求调整字段类型,此处以非空Int为例,必须设置默认值 var price: Int = 0 constructor(battery: String, brand: String) { this.battery = battery this.brand = brand } }
注意:如果ProductDTO中@Embedded注解设置了prefix参数(例如@Embedded(prefix = "attr_")),需要记住该前缀,后续修改product表字段时需要带上前缀。
2. 编写数据库Migration逻辑
假设原有数据库版本为1,需要升级到2,迁移代码如下:
val MIGRATION_1_2 = object : Migration(1, 2) { override fun migrate(database: SupportSQLiteDatabase) { // 1. 给独立的attributes表新增price字段,字段类型、默认值必须和代码定义保持一致 database.execSQL("ALTER TABLE attributes ADD COLUMN price INTEGER NOT NULL DEFAULT 0") // 2. 给product表新增嵌套AttributesDTO对应的price字段 // 如果@Embedded加了prefix="attr_",此处字段名需要改为attr_price database.execSQL("ALTER TABLE product ADD COLUMN price INTEGER NOT NULL DEFAULT 0") } }
字段类型参考:如果Price是String类型用TEXT,浮点型用REAL;如果是可空类型去掉NOT NULL,DEFAULT设置为NULL即可。
3. 注册Migration并升级数据库版本
首先修改RoomDatabase注解的版本号:
// 把version从旧版本号升级为2 @Database(entities = [ProductDTO::class, AttributesDTO::class], version = 2) abstract class AppDatabase : RoomDatabase() { // 原有DAO定义保持不变 }
然后在数据库初始化的builder中添加迁移规则:
Room.databaseBuilder(context, AppDatabase::class.java, "你的数据库名称") .addMigrations(MIGRATION_1_2) .build()
补充说明
- 如果你不需要把AttributesDTO作为独立表存储,可以删掉AttributesDTO上的
@Entity注解,迁移时只需要执行修改product表的SQL语句即可 - 可以在模块build.gradle中开启Room schema导出,方便核对表结构差异:
android { defaultConfig { javaCompileOptions { annotationProcessorOptions { arguments += ["room.schemaLocation": "$projectDir/schemas".toString()] } } } }
编译后可以在项目schemas目录下查看不同版本的表结构定义,确认字段名是否正确。
内容的提问来源于stack exchange,提问作者edi233
相关产品推荐
相关产品推荐

