GreenDao3.0 · 数据库升级/新增与修改表

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/Maiduoudo/article/details/100099960

GreenDao3.0在数据库表修改表字段(也就是实体类对字段的修改),新增表(也就是新增实体类),都要进行GreenDao3.0数据库版本的修改其他升级配置。那么版本在哪里呢?

版本位置:

1.app->build.gradle文件:

2.上图中 daoPackage配置路径下->DaoMaster文件:

注意:

GreenDao3.0 增加或者修改数据类的字段的时候,增加字段只能增加String 类型

GreenDao数据库升级

修改/新增表

第1步:升级数据库版本号

app->build.gradle文件中对android - > greendao -> schemaVersion 值做+1处理

android {
    compileSdkVersion 25
    useLibrary 'org.apache.http.legacy'
    defaultConfig {
        applicationId "com.sr.kywg"
        minSdkVersion 16
        targetSdkVersion 25     
    }
  

    greendao {       
        schemaVersion 2  //数据库的schema版本,也可以理解为数据库版本号,升级版本号 + 1
        //设置DaoMaster、DaoSession、Dao包名,也就是要放置这些类的包的全路径。
        daoPackage 'com.demo.gd.greendao'
        //设置DaoMaster、DaoSession、Dao目录
        targetGenDir 'src/main/java'
//        generateTests false //设置为true以自动生成单元测试。
//        targetGenDirTests 'src/main/java' //应存储生成的单元测试的基本目录。默认为 src / androidTest / java。
    }


  
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
  
}

第2步:修改数据库对应的实体类

@Entity
public class Person {

    @Id(autoincrement = true)
    private Long id;

    @NotNull
    private String name;

    private Integer age; // 增加一个年龄字段
}

                                

 

第3步:自定义OpenHelper对象(重写数据库升级方法)

然后,新增加表的时候(也就是增加一个新的数据类),需要在升级这里设置一下,必须把这个 

  •      DaoMaster.createAllTables(db, true);  //第二个参数改成ture
  •      DaoMaster.dropAllTables(db, true);   //第二个参数改成ture

不然会报Caused by: android.database.sqlite.SQLiteException: no such table: 表名  

/**
 * CN:      GreenDaoUpgradeHelper
 * Author: DINGCL ([email protected])
 * Date:   
 * Des:    数据库升级辅助类
 */
public class GreenDaoUpgradeHelper extends DaoMaster.OpenHelper {
    public GreenDaoUpgradeHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
        super(context, name, factory);
    }
    //这里重写onUpgrade方法
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        MigrationHelper.migrate(db, new MigrationHelper.ReCreateAllTableListener() {
            @Override
            public void onCreateAllTables(Database db, boolean ifNotExists) {
                DaoMaster.createAllTables(db, true);
            }

            @Override
            public void onDropAllTables(Database db, boolean ifExists) {
                DaoMaster.dropAllTables(db, true);
            }
            //注意此处的参数StudentDao.class,很重要(一开始没注意,给坑了一下),它就是需要升级的table的Dao,
            //不填的话数据丢失,
            // 这里可以放多个Dao.class,也就是可以做到很多table的安全升级
        }, NFCInfoBeanDao.class);
    }
}

特殊说明

其中,MigrationHelper是一个GreenDao3.0升级辅助框架。

      - 在 app -> build.gradle -> dependencies 下进行引入框架依赖:

implementation 'com.github.yuweiguocn:GreenDaoUpgradeHelper:v2.0.0'

第4步:替换默认的DevOpenHelper

public class BaseApplication extends Application{

    @Override
	public void onCreate() {
		super.onCreate();
		
		//GreenDao初始化及配置
		setDatabase();
    }

    
    /**
     * 配置greenDao
     */
	private void setDatabase() {

		// 通过DaoMaster 的内部类 DevOpenHelper,你可以得到一个便利的SQLiteOpenHelper 对象。
		// 可能你已经注意到了,你并不需要去编写「CREATE TABLE」这样的 SQL 语句,因为greenDAO。
		// 注意:默认的DaoMaster.DevOpenHelper 会在数据库升级时,删除所有的表,意味着这将导致数据的丢失。
		// 所以,在正式的项目中,你还应该做一层封装,来实现数据库的安全升级。
		GreenDaoUpgradeHelper mHelper = new GreenDaoUpgradeHelper(this,"KYWG-db", null);
		db = mHelper.getWritableDatabase();
		// 注意:该数据库连接属于DaoMaster,所以多个 Session 指的是相同的数据库连接。
		mDaoMaster = new DaoMaster(db);
		mDaoSession = mDaoMaster.newSession();

	}

	public DaoSession getDaoSession() {
		return mDaoSession;
	}
	public SQLiteDatabase getDb() {
		return db;
	}

}

 

重新编译并运行工程,即可完成数据库升级。

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)

参考资料:GreenDAO schema update and data migration?


增加表,获取等基本用法、,请自行查阅官网进行使用,注意操作这些步骤之前请先进行数据升级操作及配置



作者:maiduoduo

邮箱:[email protected] /  [email protected]

Github:

CSDN:

猜你喜欢

转载自blog.csdn.net/Maiduoudo/article/details/100099960