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();
相关推荐
黄筱筱筱筱筱筱筱2 小时前
7.适合新手小白学习Python的异常处理(Exception)
java·前端·数据库·python
Stecurry_302 小时前
Springboot整合SpringMVC --从0到1
java·spring boot·后端
Serene_Dream2 小时前
NIO 的底层机理
java·jvm·nio·mmap
skywalker_112 小时前
多线程&JUC
java·开发语言·jvm·线程池
黎雁·泠崖2 小时前
Java基础核心能力总结:从语法到API的完整知识体系
java·开发语言
_周游2 小时前
Java8 API 文档搜索引擎_2.索引模块(实现细节)
java·搜索引擎·intellij-idea
鱼跃鹰飞2 小时前
大厂面试真题-说说Kafka消息的不重复和不丢失
java·分布式·kafka
A懿轩A2 小时前
【Maven 构建工具】Maven 依赖管理详解:坐标、传递、作用域与依赖冲突解决(一篇搞懂)
java·linux·maven
2601_949543012 小时前
Flutter for OpenHarmony垃圾分类指南App实战:资讯详情实现
android·java·flutter