Home > database >  Android Room migration with Dagger 2
Android Room migration with Dagger 2

Time:12-10

I'm using Android Room 2.3.0 and Dagger 2.

DBModule.kt that provides database instance looks like this:

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

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?

CodePudding user response:

Just add the migrations to the DBModule.kt class, before calling .build().

Be careful with .fallbackToDestructiveMigration() though.

  • Related