Room is a popular Android library for local data persistence, and database migrations are essential when you need to make changes to your database schema. Migrations allow you to update the database schema without losing existing data. Here’s a step-by-step guide on how to perform a Room database migration with code:
- Create or Update Entity Classes:
If you need to modify your database schema, start by updating your entity classes. Add or remove fields as needed. - Update Database Version:
Open yourRoomDatabase
class (usually named something likeAppDatabase
) and increase the version number. This signals to Room that a migration is necessary.
@Database(entities = {YourEntity.class}, version = 2)
public abstract class AppDatabase extends RoomDatabase {
// ...
}
- Create a Migration Class:
Create a Java or Kotlin class to define the migration. This class should implement theMigration
interface, which requires you to override themigrate
method.
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;
public class MigrationFrom1To2 extends Migration {
public MigrationFrom1To2() {
super(1, 2);
}
@Override
public void migrate(SupportSQLiteDatabase database) {
// Add your SQL statements to update the schema here.
// For example, if you need to add a new column:
// database.execSQL("ALTER TABLE YourEntity ADD COLUMN new_column_name TYPE");
}
}
- Apply the Migration:
In yourRoomDatabase
class, add the migration you created using theaddMigrations
method. You can do this in the database builder’sfallbackToDestructiveMigration
method, which allows Room to apply your migration or fall back to a destructive migration (data loss) if it can’t find a suitable migration path.
@Database(entities = {YourEntity.class}, version = 2)
public abstract class AppDatabase extends RoomDatabase {
// ...
public static final Migration MIGRATION_1_2 = new MigrationFrom1To2();
public static AppDatabase getInstance(Context context) {
return Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "database-name")
.addMigrations(MIGRATION_1_2)
.fallbackToDestructiveMigration()
.build();
}
}
- Testing:
Before deploying your app with the migration, test it thoroughly to ensure that the migration works as expected and that no data loss occurs.
That’s it! You’ve successfully added a migration to your Room database. When you increment the version number and provide the appropriate migration steps, Room will automatically apply the migration the next time the database is opened.
Remember to create a new migration class for each version change, and keep track of your migrations as your database schema evolves. This helps maintain data integrity while your app continues to evolve.