在 Room 中使用 Migration 遷移工具 升級(jí)數(shù)據(jù)庫步驟 :
如果不想提供遷移策略终蒂,直接進(jìn)行破壞性升級(jí)(不保留之前的數(shù)據(jù))仿便,可以直接使用 fallbackToDestructiveMigration()
- 更新數(shù)據(jù)模型 :
如果要 更改數(shù)據(jù)庫的結(jié)構(gòu) , 更新 Entity 實(shí)體類 , 修改實(shí)體類就是修改數(shù)據(jù)庫表結(jié)構(gòu) ; 修改 Dao 數(shù)據(jù)庫訪問接口對(duì)象 , 包括添加 / 刪除 / 修改 表 / 列 / 索引 ; - 創(chuàng)建遷移類 :
創(chuàng)建一個(gè)用于執(zhí)行數(shù)據(jù)庫遷移的 遷移類 Migration , Migration 遷移類應(yīng) 實(shí)現(xiàn) Room 的 Migration 接口 , 并 定義數(shù)據(jù)庫從舊版本遷移到新版本的操作 ; - 指定遷移規(guī)則 :
在 Room 數(shù)據(jù)庫的構(gòu)建器中 , 使用 addMigrations 方法指定遷移規(guī)則 , 該方法接受一組 Migration 遷移對(duì)象 , 每個(gè) Migration 遷移對(duì)象 代表一個(gè)數(shù)據(jù)庫版本之間的遷移操作 ; - 執(zhí)行遷移 :
當(dāng)應(yīng)用程序啟動(dòng)并訪問數(shù)據(jù)庫時(shí),Room 將自動(dòng)檢測數(shù)據(jù)庫版本并執(zhí)行適當(dāng)?shù)倪w移操作 , 應(yīng)用程序可以無縫地將舊版本的數(shù)據(jù)庫遷移到新版本害驹,而不會(huì)丟失現(xiàn)有的數(shù)據(jù)柑蛇。
自動(dòng)升級(jí)
exportSchema必須設(shè)置為true(默認(rèn)為true),否則會(huì)出現(xiàn)如下報(bào)錯(cuò)
Cannot create auto migrations when export schema is OFF.
首先需要在@Database
注解中增加autoMigrations
@Database(entities = {User.class, Book.class}, version = 3,exportSchema = true,autoMigrations = @AutoMigration(from = 2,to = 3,spec = UserRoomDatabase.TestAutoMigration.class))
如果 Room 發(fā)現(xiàn)遷移過程中有歧義棋弥,并且在未提供更多信息的時(shí)候無法制定確切的自遷移方案,在編譯期間就會(huì)發(fā)生錯(cuò)誤诚欠,這時(shí)開發(fā)者需要提供一個(gè) AutoMigrationSpec 的實(shí)現(xiàn)顽染。多數(shù)情況下漾岳,自遷移發(fā)生錯(cuò)誤都是由下列的原因造成的。
- 刪除或者重命名數(shù)據(jù)表名
- 刪除或者重命名數(shù)據(jù)表的列名
@RenameColumn(tableName = "user_table", fromColumnName = "job", toColumnName = "user_job")
static class TestAutoMigration implements AutoMigrationSpec { }
AutoMigrationSpec 實(shí)現(xiàn)類的注解
手動(dòng)升級(jí)
//修改version = 2
@Database(entities = {User.class, Book.class}, version = 2,exportSchema = true)
創(chuàng)建具體的版本遷移策略
//添加字段 具體的版本遷移策略
public static final Migration MIGRATION_1_2 = new Migration(1, 2) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
//添加字段
// database.execSQL("ALTER TABLE user_table ADD COLUMN job TEXT NOT NULL DEFAULT '民工'");
database.execSQL("ALTER TABLE user_table ADD COLUMN job TEXT");
// database.execSQL("ALTER TABLE user_table RENAME COLUMN job TO user_job");
}
};
//單例創(chuàng)建database
static UserRoomDatabase getDatabase(final Context context) {
if (INSTANCE == null) {
synchronized (UserRoomDatabase.class) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(
context.getApplicationContext(),
UserRoomDatabase.class, DATABASE_NAME)
.addMigrations(MIGRATION_1_2)////添加完了migration后粉寞,根據(jù)Room.builder把我們版本更新的信息add進(jìn)去
.build();
}
}
}
return INSTANCE;
}
補(bǔ)充
exportSchema
設(shè)置為 true
后尼荆,會(huì)在指定路徑(app的build.gradle里設(shè)置的)下生成一個(gè)json文件,里面有不同版本的表的信息唧垦。 AutoMigrationSpec 實(shí)現(xiàn)類的注解
json文件所在位置.jpg