默认的 DevOpenHelper 不能用,数据库版本号改变时每次都是删除重建
/** WARNING: Drops all table on Upgrade! Use only during development. */
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);
}
}
其实之前直接继承 SQLiteOpenHelper 怎么升级现在就怎么升级,因为 greendao 的 OpenHelper 也是继承了 SQLiteOpenHelper 简单扩展了一下而已
所以我们再自己写一个 OpenHelper 重写 onUpgrade 就可以了
public class SQLiteOpenHelper extends DaoMaster.OpenHelper {
private static HashMap<Integer, Migration> ALL_MIGRATIONS = new HashMap<>();
static {
// 每一个数据库版本对应一个这个版本的升级脚本
ALL_MIGRATIONS.put(2, new V2Migration());
}
public SQLiteOpenHelper(Context context, String name) {
super(context, name);
}
public SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
Log.d("db", "oldVersion " + oldVersion + " newVersion " + newVersion);
Set versionSet = ALL_MIGRATIONS.keySet();
// 从当前版本的下一个版本到最新版本的所有的迁移脚本都要跑一遍
// 如当前数据库版本是 2 ,现在要装一个版本号是 5 的 app, 则 3 4 5 的迁移脚本都要跑一遍
for (int v = oldVersion + 1; v <= newVersion; v++) {
if (versionSet.contains(v)) {
ALL_MIGRATIONS.get(v).migrate(db);
}
}
}
interface Migration {
void migrate(Database db);
}
static class V2Migration implements Migration {
@Override
public void migrate(Database db) {
db.execSQL("alter table " + NoteDao.TABLENAME + " add column " + NoteDao.Properties.Age.columnName + " int");
}
}
}
使用
ProOpenHelper helper = new ProOpenHelper(this, "hj-db");
Database db = helper.getWritableDb();
daoSession = new DaoMaster(db).newSession();