Android 开发 Room 数据库升级问题:A migration from 6 to 7 was required but not found.

  • 在 Android 开发中,使用 Room 时,出现如下错误信息

    java.lang.IllegalStateException:
    A migration from 6 to 7 was required but not found.
    Please provide the necessary Migration path via RoomDatabase.Builder.addMigration(Migration ...) or allow for destructive migrations via one of the RoomDatabase.Builder.fallbackToDestructiveMigration* methods.

    解读

    java.lang.IllegalStateException:
    需要从版本 6 到版本 7 的迁移策略,但未找到
    请通过 RoomDatabase.Builder.addMigration(Migration ...) 提供必要的迁移路径
    或者通过 RoomDatabase.Builder.fallbackToDestructiveMigration* 方法之一允许破坏性迁移

问题原因
  • 使用 Room 将数据库从版本 6 升级到版本 7,但没有提供对应的迁移策略
处理策略
  1. 通过 addMigration 方法提供必要的迁移策略(推荐)
java 复制代码
private static final Migration MIGRATION_6_7 = new Migration(6, 7) {

    @Override
    public void migrate(@NonNull SupportSQLiteDatabase database) {
        
        ...

    }
};
java 复制代码
MyDatabase myDatabase = Room.databaseBuilder(MyApplication.getContext(), MyDatabase.class, DATABASE_NAME)
        .addMigrations(MIGRATION_1_2)
        .addMigrations(MIGRATION_2_3)
        .addMigrations(MIGRATION_3_4)
        .addMigrations(MIGRATION_4_5)
        .addMigrations(MIGRATION_5_6)
        .addMigrations(MIGRATION_6_7)
        .build();
  1. 通过 fallbackToDestructiveMigration 方法允许破坏性迁移(不推荐)
java 复制代码
MyDatabase myDatabase = Room.databaseBuilder(MyApplication.getContext(), MyDatabase.class, DATABASE_NAME)
      .fallbackToDestructiveMigration()
      .build();
相关推荐
亦暖筑序9 小时前
Java 8老系统AI Workflow实战:把一次性AI对话升级成可恢复工作流
java·后端
恋猫de小郭9 小时前
Amper 正式转正 Kotlin Toolchain ,Gradle 未来何去何从
android·前端·flutter
敲代码的彭于晏9 小时前
Bean 生命周期完全图解:前端同学也能看懂的 Spring 核心机制
java·前端·后端
plainGeekDev10 小时前
ButterKnife → ViewBinding
android·java·kotlin
成都大菠萝1 天前
Android Car CarProperty 车辆信号链路
android
敲代码的鱼1 天前
PDF 预览与签名批注写回 支持安卓 iOS 鸿蒙 UTS插件
android·前端·ios
时光足迹1 天前
uni-app 视频通话实战:康复师与患者视频问诊的 6 个致命 Bug 与解决方案
android·ios·uni-app
像我这样帅的人丶你还1 天前
Java 后端详解(四):分页与搜索
java·javascript·后端
她的男孩1 天前
数据权限为什么不能只靠注解?Forge 的 Mapper 层 SQL 改写源码拆解
java·后端·架构
tntxia1 天前
Mybatis的日志输入
java