前言
在 Android ORM 框架:GreenDao 使用详解(进阶篇) 中漏讲了一个非常重要的模块 ( GreenDao 数据库升级 ),现在补上 。
一,GreenDao 默认的升级方式
GreenDao 默认的升级方式是删除所有旧版,在重新建新表,这样一来用户的本地历史数据则会丢失,这点我们通过DaoMaster 的内部类 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);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
二、自定义升级方式
1,修改 schemaVersion 版本号(schemaVersion 只能往上升,不能降)
greendao {
schemaVersion 2
daoPackage 'com.speedystone.greendaodemo.db'
targetGenDir 'src/main/java'
}
2,自定义 OpenHelper :继承 DaoMaster.OpenHelper,重新 onUpgrade 方法
/**
* Created by Speedy on 2017/7/4.
*/
public class DbHelper extends DaoMaster.OpenHelper {
public DbHelper(Context context, String name) {
super(context, name);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion );
if(newVersion == 2){
db.execSQL("ALTER TABLE 'USER' ADD 'NICKNAME' String");
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
3,在初始化GreenDao 阶段,采用自定义的 OpenHelper 替换 DaoMaster.DevOpenHelper
/**
* 初始化 GreenDao
*/
private void initGreenDao() {
DbHelper helper = new DbHelper(this,"test.db");
SQLiteDatabase db = helper.getWritableDatabase();
DaoMaster daoMaster = new DaoMaster(db);
daoSession = daoMaster.newSession();
}
三,注意事项
1, @Id 标记的ID字段,对应数据库列名会转化为 “_id ”
2, 通过注解建立的表如果没有使用 @Property 指明表列名,默认表中列名是大写单词
例如:
@Entity
public class User {
@Id
private long userId;
private String name;
@Property(nameInDb = "age")
private int age;
}
对应表结构: