Android room persistent library - How to change database version

Viewed 8766

Im not clear on how to use room after i have updated the database version.

For example, lets say i originally had the following database defined in room:

@Database(entities = {Event.class}, version = 1)
@TypeConverters(DateTypeConverter.class)
public abstract class EventDatabase extends RoomDatabase {

   public abstract EventDao eventDao();

}

and then i change the version so that it looks like this now:

@Database(entities = {Event.class}, version = 2)
@TypeConverters(DateTypeConverter.class)
public abstract class EventDatabase extends RoomDatabase {

   public abstract EventDao eventDao();

}

when i saw change the version i mean that i may have added or deleted columns in the database so its not same. my questions are the following:

do i need to maintain two databases now ? v1 and v2 ? and is there a way to copy entities easily over to v2 ? also when changing the version is it enough to simply change it from 1 to 2 or do i have to create another class called EventDatabase2 for example ?

also here is the version of room i am using:android.arch.persistence.room:runtime:1.0.0-alpha1

3 Answers

My answer may be late, but it may help someone like me who has only recently found the answer to the same question.

For some reason you need to upgrade the database version but do not need to adjust the database, as simple as editing the @Dao adapter or the @Entity attribute without affecting the structure of the database.

If you upgrade the Version in the Database as below:

From:

@Database(
    entities = [ExampleClass::class],
    version = 1,
    exportSchema = false
)

To:

@Database(
    entities = [ExampleClass::class],
    version = 2,
    exportSchema = false
)

If you do not add anything later, the database will be refreshed as if it were deleted. To avoid deletion, you can simply add an empty Migration as follows:

private val MIGRATION_1_2 = object : Migration(1, 2) {
    override fun migrate(database: SupportSQLiteDatabase) {

    }
}

build your database:

@Synchronized
private fun buildDatabase(context: Context, databaseName: String): AppDatabase {
    return Room.databaseBuilder(
        context.applicationContext,
        AppDatabase::class.java,
        databaseName
    )
        .addMigrations(MIGRATION_1_2)
        .allowMainThreadQueries()
        .fallbackToDestructiveMigration()
        .build()
}

Database data will not be affected

Related