Android Room数据库迁移正在多次运行。

5
我正在使用room数据库来创建本地存储,我尝试迁移数据库,但在调用迁移函数多次时出现问题。
以下是我的代码片段。
class DbInstance {
companion object {
    private var db: AppDatabase? = null
    fun getDbInstance(context: Context): AppDatabase {
        if (db == null)
            db = Room.databaseBuilder(
                context,
                AppDatabase::class.java, "mydb"
            )
                .addMigrations(MIGRATION_1_2, MIGRATION_2_3)
                .build()
        return db!!
    }

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

        }
    }
    private val MIGRATION_2_3 = object : Migration(2, 3) {
        override fun migrate(database: SupportSQLiteDatabase) {
            println("------> called for MIGRATION_2_3")
            database.execSQL(
                "Alter table PaymentDB add column ui_name text"
            )
        }
    }
  }
}



@Database(entities = arrayOf(PaymentDB::class), version = 3)
@TypeConverters(DbTypeConverter::class)
abstract class AppDatabase : RoomDatabase() {
    abstract fun paymentDao(): PaymentDao
}

在哪里println("------> called for MIGRATION_2_3")被多次打印了两次。


1
嗨,你找到答案了吗? - Oleksandr Berdnikov
我最终通过手动检查解决了它。 - ice spirit
可能与您的问题无关,但您应该在Room数据库中获取应用程序上下文。Room.databaseBuilder(context.applicationContext, ... - Shreyash.K
2个回答

0

我遇到了这个问题,因为我正在使用多个数据库实例。 如果可能的话,您应该坚持使用单个实例以避免此问题。在我的情况下,我需要一个单独的实例来处理小部件和通知,因为它们在与主应用程序不同的应用程序上下文中运行,并且使用单独的数据库是最简单的解决方案。

Kotlin扩展,在每次迁移之前运行:

private fun SupportSQLiteDatabase.hasAlreadyDoneMigration(migration: Migration): Boolean {
    return version >= migration.endVersion
}

使用方法:

val MIGRATION_5_TO_6: Migration = object : Migration(5, 6) {
    override fun migrate(database: SupportSQLiteDatabase) {
        if (database.hasAlreadyDoneMigration(this)) {
            return
        }
        database.beginTransaction()
        
        // your migration code here

        database.setTransactionSuccessful()
        database.endTransaction()
    }
}

迁移已在事务中执行 - undefined

0

最终通过使用这种方法得到了解决方案。

  if (DbInstance.getDbInstance(context.get()!!).openHelper.readableDatabase.version != Constants.DATABASE_VERSION) {
                        DbInstance.getDbInstance(context = context.get()!!)
                            .openHelper.readableDatabase.needUpgrade(Constants.DATABASE_VERSION)
                        DbInstance.getDbInstance(context = context.get()!!)
                            .openHelper.writableDatabase.needUpgrade(Constants.DATABASE_VERSION)
                    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接