GreenDao升级

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
  1. The class catch all the Daos that you got
  2. Creates the temporary tables based on the old version’s scheme
    (generateTempTables method)
  3. Import all the data to this new tables (generateTempTables method)
  4. Drop all the tables of the old version (DaoMaster.dropAllTables
    method)
  5. Creates the tables of the new version (DaoMaster.createAllTables
    method)
  6. Updates the new version’s tables from the temporaries (restoreData
    method)
  7. 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;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值