在App更新的过程中,不免需要升级数据库,重建或修改表结构,但是GreenDao并没有提供相应的数据库升级方法,观察GreenDao生成的DaoMaster类,可以找到解决办法。
GreenDao中数据库版本不可修改,在编译生成的DaoMaster类中,可以看到,SCHEMA_VERSION固定为1。
public class DaoMaster extends AbstractDaoMaster {
public static final int SCHEMA_VERSION = 1;
...
public static abstract class OpenHelper extends DatabaseOpenHelper {
public OpenHelper(Context context, String name) {
super(context, name, SCHEMA_VERSION);
}
public OpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory, SCHEMA_VERSION);
}
@Override
public void onCreate(Database db) {
Log.i("greenDAO", "Creating tables for schema version " + SCHEMA_VERSION);
createAllTables(db, false);
}
}
public static class DevOpenHelper extends OpenHelper {
public DevOpenHelper(Context context, String name) {
super(context, name);
}
public DevOpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropping all tables");
dropAllTables(db, true);
onCreate(db);
}
}
}
一般GreenDao初始化为:
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, ENCRYPTED ? "fpc-db-encrypted" : "fpc-db");
db = ENCRYPTED ? helper.getEncryptedWritableDb("super-secret") : helper.getWritableDb();
daoSession = new DaoMaster(db).newSession();
如果使用自带的DevOpenHelper,那么生成的数据库版本固定为SCHEMA_VERSION = 1,数据库永远不会升级。
要想升级数据库版本从而触发onUpgrade方法,需要自定义一个OpenHelper,继承org.greenrobot.greendao.database.DatabaseOpenHelper
,代码如下:
...
import org.greenrobot.greendao.database.DatabaseOpenHelper;
public class GreenOpenHelper extends DatabaseOpenHelper {
public static int DB_VERSION = BuildConfig.VERSION_CODE;
public GreenOpenHelper(Context context, String name) {
super(context, name, DB_VERSION);
}
public GreenOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
super(context, name, factory, DB_VERSION);
}
@Override
public void onCreate(Database db) {
Log.i("greenDAO", "Creating tables for schema version " + DB_VERSION);
DaoMaster.createAllTables(db, false);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropping all tables");
if (newVersion > oldVersion) {
DaoMaster.dropAllTables(db, true);
onCreate(db);
}
}
}
注意, DatabaseOpenHelper继承android.database.sqlite.SQLiteOpenHelper
,需要将数据库版本写入SQLiteOpenHelper的构造器才能生效
我们使用GreenOpenHelper替代DaoMaster.DevOpenHelper,初始化代码现在变为:
GreenOpenHelper helper = new GreenOpenHelper(this, ENCRYPTED ? "fpc-db-encrypted" : "fpc-db");
db = ENCRYPTED ? helper.getEncryptedWritableDb("super-secret") : helper.getWritableDb();
daoSession = new DaoMaster(db).newSession();
现在我们可以用BuildConfig.VERSION_CODE来控制数据库版本,需要升级数据库时在build.gradle(app模块)修改versionCode就可以了。