简体   繁体   English

Android 使用 Dagger 2 进行房间迁移

[英]Android Room migration with Dagger 2

I'm using Android Room 2.3.0 and Dagger 2.我正在使用 Android Room 2.3.0 和 Dagger 2。

DBModule.kt that provides database instance looks like this:提供数据库实例的DBModule.kt如下所示:

@Singleton
@Provides
open fun provideDatabase(context: Context): AppDatabase {
    return Room.databaseBuilder<AppDatabase>(
        context.applicationContext, AppDatabase::class.java,
        DATABASE_NAME
    ).fallbackToDestructiveMigration().build()
}

AppDatabase.kt class: AppDatabase.kt class:

@Database(
    entities = [User::class],
    version = 1,
    exportSchema = false
)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao
}

Now I need to add a few new columns into User entity and increase db version.现在我需要在用户实体中添加一些新列并增加数据库版本。 How can I do a migration in AppDatabase.kt and call .addMigrations() if I don't have access to Room.databaseBuilder from AppDatabase.kt ?如果我无法从AppDatabase.kt访问 Room.databaseBuilder,如何在AppDatabase.kt中进行迁移并调用.addMigrations()

Just add the migrations to the DBModule.kt class, before calling .build() .只需在调用 .build .build()之前将迁移添加到DBModule.kt class 即可。

Be careful with .fallbackToDestructiveMigration() though.不过要小心.fallbackToDestructiveMigration()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM