dependencies {
def room_version = "2.2.5"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
androidTestImplementation "androidx.room:room-testing:$room_version"
}
val migration1to2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE User ADD COLUMN age INTEGER NOT NULL DEFAULT 0")
}
}
val db = Room.inMemoryDatabaseBuilder(
InstrumentationRegistry.getInstrumentation().context,
MyDatabase::class.java
).addMigrations(migration1to2)
.build()
db.openHelper.writableDatabase
其中,MyDatabase 是 Room Database 的子类。
val user = User("Alice")
db.userDao().insert(user)
val loaded = db.userDao().findById(user.id)
assertThat(loaded.age, equalTo(0))
其中,User 和 UserDao 分别为 Room Entity 和 Dao 的子类。注意,由于 age 是新添加的列,默认值为 0。
db.close()