안드로이드 공식 페이지 - Room 데이터베이스 이전
기존 Room DB 구성
더보기
@Database(
entities = [Alarm::class, MedicationHistory::class],
version = 1
)
abstract class AppDatabase : RoomDatabase() {
abstract fun alarmDao(): AlarmDao
abstract fun medicationHistoryDoa(): MedicationHistoryDao
companion object {
@Volatile
private var instance: AppDatabase? = null
fun getDatabase(context: Context): AppDatabase =
instance ?: synchronized(this) {
instance ?: buildDatabase(context).also {
instance = it
}
}
private fun buildDatabase(appContext: Context) =
Room.databaseBuilder(appContext, AppDatabase::class.java, "app_db")
.build()
}
}
기존 Room 마이그레이션 방법
@Database(
version = AppDatabase.LATEST_VERSION,
entities = [Alarm::class]
)
abstract class AppDatabase : RoomDatabase() {
abstract fun alarmDao(): AlarmDao
companion object {
@Volatile
private var instance: AppDatabase? = null
fun getDatabase(context: Context): AppDatabase =
instance ?: synchronized(this) {
instance ?: buildDatabase(context).also {
instance = it
}
}
private fun buildDatabase(appContext: Context) =
Room.databaseBuilder(appContext, AppDatabase::class.java, "app_db")
.addMigrations(MIGRATION_1_2)
.build()
private val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("DROP TABLE 테이블이름")
}
}
const val LATEST_VERSION = 2
}
}
AutoMigration 사용하는 마이그레이션 방법
@Database(
version = AppDatabase.LATEST_VERSION,
entities = [Alarm::class],
autoMigrations = [
AutoMigration(
from = 1,
to = 2,
spec = AppDatabase.IhpMigration::class
)
],
exportSchema = true
)
abstract class AppDatabase : RoomDatabase() {
abstract fun alarmDao(): AlarmDao
@DeleteTable(tableName = "테이블이름")
class IhpMigration : AutoMigrationSpec {}
companion object {
@Volatile
private var instance: AppDatabase? = null
fun getDatabase(context: Context): AppDatabase =
instance ?: synchronized(this) {
instance ?: buildDatabase(context).also {
instance = it
}
}
private fun buildDatabase(appContext: Context) =
Room.databaseBuilder(appContext, AppDatabase::class.java, "inhandplus")
.build()
const val LATEST_VERSION = 2
}
}
반응형
'Dev > Android' 카테고리의 다른 글
Jetpack Compose 학습 (0) | 2022.08.16 |
---|---|
Kotlin Gson 활용해서 Json 파싱하는 방법 (0) | 2022.07.28 |
Retrofit2 이슈 - com.google.gson.JsonIOException: JSON document was not fully consumed. (0) | 2022.04.25 |
[AndroidStudio] 사용중이던 Github 계정 바꾸기 (0) | 2022.03.30 |
Jetpack Compose - 1 (0) | 2022.03.30 |