Junior — Middle
How to implement database migration when using Room in Android?
sobes.tech AI
Answer from AI
To implement a database migration when using Room in Android, you need to:
- Create a new version of the database by increasing the
versionvalue in the@Databaseannotation. - Define a migration class that implements the
Migrationinterface, where you describe SQL commands for schema transformation in themigrate()method. - Pass the migration object to the Room builder when creating the database via the
addMigrations()method.
Example of migration from version 1 to 2:
val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE users ADD COLUMN age INTEGER DEFAULT 0 NOT NULL")
}
}
val db = Room.databaseBuilder(context, AppDatabase::class.java, "app-db")
.addMigrations(MIGRATION_1_2)
.build()
Thus, when updating the version, Room will apply the migration and preserve the data.