【问题标题】:Room Database migration for all version所有版本的房间数据库迁移
【发布时间】:2021-12-11 13:07:14
【问题描述】:

目前我的数据库版本是5,我已经在数据库表中添加了列并将数据库版本更改为6,并且还添加了从版本5到6的迁移,就像这样

 private static final Migration MIGRATION_5_6 = new Migration(5, 6) {
        @Override
        public void migrate(SupportSQLiteDatabase database) {
            try {
                database.execSQL("ALTER TABLE generate_data "
                        + " ADD COLUMN generateImgPath TEXT");
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    };

问题:我需要为每个版本制作迁移对象吗?

喜欢

MIGRATION_1_6 
MIGRATION_2_6
MIGRATION_3_6
MIGRATION_4_6
MIGRATION_5_6

【问题讨论】:

    标签: android android-room database-migration


    【解决方案1】:

    我需要为每个版本制作迁移对象吗?

    不,您不必为所有以前的版本创建迁移对象到最新版本。您只需创建一个从倒数第二个版本到最新版本的迁移对象。

    但是,对于使用旧数据库版本的迁移用户,您必须为每个连续版本添加migration,例如

    MIGRATION_1_2
    MIGRATION_2_3
    MIGRATION_3_4
    MIGRATION_4_5
    MIGRATION_5_6
    

    因此,如果任何用户使用的是最旧版本的database,那么Room 将运行所有连续的migrations 并将其更新到最新版本。


    如果您只是将新的column 添加到table,则从版本 5 到版本 6 的数据库。您可以使用autoMigration,因此您不必手动定义migration 策略。

    对于使用autoMigration,例如从版本5到版本6,将版本更改为6,并将autoMigration添加到database注解中。

    @Database(
       version = 5,
       entities = [ table.class ],
       autoMigrations = [
             AutoMigration (from = 5, to = 6)
         ]
      )
    abstract class YourDatabase: RoomDatabase { }
    

    假设你在未来的版本 7 中也添加了一个新列,那么你可以在 autoMigrations 中添加另一个 AutoMigration 对象

     autoMigrations = [
                 AutoMigration (from = 5, to = 6),
                 AutoMigration (from = 6, to = 7)
             ]
    

    【讨论】:

    • 谢谢,我试试这个
    猜你喜欢
    • 2019-02-13
    • 2021-08-13
    • 2021-09-02
    • 2020-08-19
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 1970-01-01
    相关资源
    最近更新 更多