美文网首页
GreenDao 3.0的基本用法以及正确的数据库版本升级

GreenDao 3.0的基本用法以及正确的数据库版本升级

作者: GexYY | 来源:发表于2018-07-12 16:52 被阅读0次

1: Gradle配置

在项目根目录中的build.gradle和主model(app)工程下的build.gradle分别加入如下配置:

dependencies {
        classpath 'com.android.tools.build:gradle:3.1.3'
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin
    }
greendao {
    schemaVersion 5 //数据库版本号
    daoPackage 'com.gx.greendao' //设置DaoMaster.DaoSession,Dao包名
    targetGenDir 'src/main/java' //设置daoPackage所在的文件路径
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:27.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:recyclerview-v7:27.1.0'
    implementation 'com.android.support:support-v4:27.1.0'
    compile 'com.android.support:design:27.1.0'
   
    implementation 'org.greenrobot:greendao:3.2.2' // add library

}

2: 项目实战运用

新建User的java实体类,如下:

@Entity
public class User {
    @Id(autoincrement = true)
    private Long id;
    private String name;
    private int age;
    private String pic;
    private String content;
}

然后执行Build->Make Model app ,会自动根据配置在项目中对应的com.gx.greendao目录下生成DaoMaster``DaoSession``UserDao三个文件

image.png

在项目的application中完成相应的初始化操作,如下:

 private String DATA_BASE_NAME = "GxDb";
    private static DaoSession mDaoSession;

    @Override
    public void onCreate() {
        super.onCreate();
        setUpDataBase(this);
    }

    private void setUpDataBase(Context context) {
        DaoMaster.DevOpenHelper openHelper = new DaoMaster.DevOpenHelper(context, DATA_BASE_NAME);
        Database db = openHelper.getWritableDb();
        DaoMaster daoMaster = new DaoMaster(db);


        mDaoSession = daoMaster.newSession();
    }

    public static DaoSession getDaoSession() {
        return mDaoSession;
    }

增删改查操作:

               //插入
                User user = new User(null, "GexYY" + new Random().nextInt(100), new Random().nextInt(40) + 20,"content","csd");
                mUserDaoSession.getUserDao().insert(user);
                mQueryBtn.performClick();
              
                //删除
                mUserDaoSession.getUserDao().deleteByKey(1l);
                mQueryBtn.performClick();
    
                //更新
                User user1 = mUserDaoSession.getUserDao().load(1l);
                if (user1 != null) {
                    user1.setName("GexYY_Update");
                    mUserDaoSession.getUserDao().update(user1);
                }
               
                //查询
                List<User> userList = mUserDaoSession.getUserDao().loadAll();
                StringBuilder builder = new StringBuilder();
                for (User entity : userList) {
                    builder.append(entity.toString()).append("\n");
                }
                mContent.setText(builder.toString());
               

3: 数据库升级

GreenDao默认帮我们处理来升级操作,只需要在build.gradle中修改一下schemaVersion版本号即可

但是我们查看DaoMaster.DevOpenHelper的代码中的onUpgragde()方法如下:

 @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);
        }

发现每次升级都是把老的数据库删除掉,包括数据,然后再重新创建相关的数据库和表,这样就导致了数据库升级之后数据的丢失.
那么如何保证升级后数据的不丢失呢?
这里就用到了一个大神写的MigrationHelper
https://stackoverflow.com/questions/13373170/greendao-schema-update-and-data-migration/30334668#30334668
使用方法如下:

@Override
    public void onUpgrade(Database db, int oldVersion, int newVersion) {
        if (oldVersion < newVersion) {
            DbBackUpHelper.getInstance().migrate(db, UserDao.class);
        }
    }

但是由于DaoMaster.DevOpenHelper是编译自动生成的,所以不建议直接在其里边去实现,这样每次编译都会把相关代码还原删除,
我们应该自定义一个openHelper,并继承'DaoMaster.DevOpenHelper',如下:

public class DbOpenHelper extends DaoMaster.DevOpenHelper {
    public DbOpenHelper(Context context, String name) {
        super(context, name);
    }

    public DbOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
        super(context, name, factory);
    }

    @Override
    public void onUpgrade(Database db, int oldVersion, int newVersion) {
       //切记不要调用super.onUpgrade(db,oldVersion,newVersion)
        if (oldVersion < newVersion) {
            DbBackUpHelper.getInstance().migrate(db, UserDao.class);
        }
    }
}

切记不要调用super.onUpgrade(db,oldVersion,newVersion),不然依然会删除数据记录

然后在修改一下初始化地方的代码如下:

private void setUpDataBase(Context context) {
        DbOpenHelper openHelper = new DbOpenHelper(context, DATA_BASE_NAME, null);
        Database db = openHelper.getWritableDb();
        DaoMaster daoMaster = new DaoMaster(db);
        mDaoSession = daoMaster.newSession();
    }

到此,GreenDao的数据库升级就优化结束,并且能正常保留表数据!

关于实体的相关注解,请参考http://www.cnblogs.com/zhujiabin/p/9288492.html

相关文章

网友评论

      本文标题:GreenDao 3.0的基本用法以及正确的数据库版本升级

      本文链接:https://www.haomeiwen.com/subject/vllrpftx.html