使用 greendao 中的 OpenHelper 升级数据库

Ser*_*Cna 5 database sqlite android greendao

我使用 GreenDao 作为我的 ORM。我想将架构从旧版本迁移到新版本。我使用此链接来实现我的 mygration。所以我编写了自己的 OpenHelper 类并将其放入另一个包中。我像这样实现 onUpgrade 方法:

public class UpgradeHelper extends OpenHelper {

public UpgradeHelper(Context context, String name, CursorFactory factory) {
    super(context, name, factory);
}

/**
 * Apply the appropriate migrations to update the database.
 */
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.i("greenDAO", "My Upgrade Helper -------- Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropping all tables");
    switch (newVersion) {
    case 2:
        new MigrateV1ToV2().applyMigration(db, oldVersion);
        break;
    case 3:
        new MigrateV2ToV3().applyMigration(db, oldVersion);
        break;
    default:
        return;
    }
}
Run Code Online (Sandbox Code Playgroud)

}

但是当我将数据库版本从1升级到2时,这个方法从未被调用。而且我也无法更改生成的DaoMaster类中的onUpgrade()方法,因为它是自动生成的。当我升级 SCHEMA_VERSION 时,会调用 onUpgrade() 方法,但它位于 DaoMaster 类中,我无法修改它。

Ale*_*exS 3

仅当SQLite 数据库中存储的数据与您在代码中指定的数据不同时onUpgrade(Database, oldSchemaVersion, newSchemaVersion),才会调用 - 方法。SCHEMA-VERSIONSCHEMA-VERSION

因此,此方法对于数据库的每个版本仅运行一次。如果您忘记在第一次运行中包含更新逻辑,则必须手动重置架构版本,例如使用SQLiteManager