GreenDao数据库升级
第1步:升级数据库版本号
// app:build.gradle
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao'
android {
...
}
greendao{
schemaVersion 2 // 版本号+1
}
dependencies {
...
}
第2步:修改数据库实体类
@Entity
public class Person {
@Id(autoincrement = true)
private Long id;
@NotNull
private String name;
private Integer age; // 增加一个年龄字段
}
第3步:迁移数据库
注:数据库升级不可使用GreenDao默认生成的DaoMaster.DevOpenHelper,因为DaoMaster.DevOpenHelper在数据库升级时会删除数据库再重新创建。
因此,我们需要继承DaoMaster.OpenHelper实现自己的MyOpenHelper,在onUpgrade()方法中升级数据库。
// 继承DaoMaster.OpenHelper
public class MyOpenHelper extends DaoMaster.OpenHelper {
public MyOpenHelper(Context context, String name) {
super(context, name);
}
public MyOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
super.onUpgrade(db, oldVersion, newVersion);
// 迁移数据库(如果修改了多个实体类,则需要把对应的Dao都传进来)
MigrationHelper.migrate(db, PersonDao.class);
}
}
重新编译并运行工程,即可完成数据库升级。
## Migration Helper class
- The class catch all the Daos that you got
- Creates the temporary tables based on the old version’s scheme
(generateTempTables method) - Import all the data to this new tables (generateTempTables method)
- Drop all the tables of the old version (DaoMaster.dropAllTables
method) - Creates the tables of the new version (DaoMaster.createAllTables
method) - Updates the new version’s tables from the temporaries (restoreData
method) - Drop all temporary tables (restoreData method)
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.StandardDatabase;
import org.greenrobot.greendao.internal.DaoConfig;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;