GreenDAO数据库版本升级

GreenDAO是一款非要流行的android平台上的数据库框架,性能优秀,代码简洁。 
初始化数据库模型代码的时候需要使用java项目生成代码,依赖的jar包已经上传到我的资源里了,下载地址如下:http://download.csdn.net/detail/fancylovejava/8859203

项目开发中用到的就是GreenDAO数据库框架,需要进行数据库版本升级。 
其实数据库版本升级比较麻烦的就是数据的迁移,data migration。

数据库版本升级有很多方法,按不同需求来处理。

本质上是去执行sql语句去创建临时数据表,然后迁移数据,修改临时表名等。

数据版本升级,为了便于维护代码可以先定义一个抽象类

public abstract class AbstractMigratorHelper {

public abstract void onUpgrade(SQLiteDatabase db);
}

然后让自己更新数据库逻辑的类继承这个类

public class DBMigrationHelper6 extends AbstractMigratorHelper {

/* Upgrade from DB schema 6 to schema 7 , version numbers are just examples*/

public void onUpgrade(SQLiteDatabase db) {

    /* Create a temporal table where you will copy all the data from the previous table that you need to modify with a non supported sqlite operation */
    db.execSQL("CREATE TABLE " + "‘post2‘ (" + //
            "‘_id‘ INTEGER PRIMARY KEY ," + // 0: id
            "‘POST_ID‘ INTEGER UNIQUE ," + // 1: postId
            "‘USER_ID‘ INTEGER," + // 2: userId
            "‘VERSION‘ INTEGER," + // 3: version
            "‘TYPE‘ TEXT," + // 4: type
            "‘MAGAZINE_ID‘ TEXT NOT NULL ," + // 5: magazineId
            "‘SERVER_TIMESTAMP‘ INTEGER," + // 6: serverTimestamp
            "‘CLIENT_TIMESTAMP‘ INTEGER," + // 7: clientTimestamp
            "‘MAGAZINE_REFERENCE‘ TEXT NOT NULL ," + // 8: magazineReference
            "‘POST_CONTENT‘ TEXT);"); // 9: postContent

    /* Copy the data from one table to the new one */
    db.execSQL("INSERT INTO post2 (_id, POST_ID, USER_ID, VERSION, TYPE,  MAGAZINE_ID, SERVER_TIMESTAMP, CLIENT_TIMESTAMP, MAGAZINE_REFERENCE, POST_CONTENT)" +
            "   SELECT _id, POST_ID, USER_ID, VERSION, TYPE,  MAGAZINE_ID, SERVER_TIMESTAMP, CLIENT_TIMESTAMP, MAGAZINE_REFERENCE, POST_CONTENT FROM post;");

    /* Delete the previous table */
    db.execSQL("DROP TABLE post");
    /* Rename the just created table to the one that I have just deleted */
    db.execSQL("ALTER TABLE post2 RENAME TO post");

    /* Add Index/es if you want them */
    db.execSQL("CREATE INDEX " + "IDX_post_USER_ID ON post" +
            " (USER_ID);");
    //Example sql statement
    db.execSQL("ALTER TABLE user ADD COLUMN USERNAME TEXT");
   }
}

最后在OpenHelper方法里的OnUpgrade方法里面处理,这里方法调用的比较巧妙,借用国外大牛的代码复制下。

public static class UpgradeHelper extends OpenHelper {

    public UpgradeHelper(Context context, String name, CursorFactory factory) {
        super(context, name, factory);
    }

    /**
     * Here is where the calls to upgrade are executed
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        /* i represent the version where the user is now and the class named with this number implies that is upgrading from i to i++ schema */
        for (int i = oldVersion; i < newVersion; i++) {
            try {
                /* New instance of the class that migrates from i version to i++ version named DBMigratorHelper{version that the db has on this moment} */
                AbstractMigratorHelper migratorHelper = (AbstractMigratorHelper) Class.forName("com.nameofyourpackage.persistence.MigrationHelpers.DBMigrationHelper" + i).newInstance();

                if (migratorHelper != null) {

                    /* Upgrade de db */
                    migratorHelper.onUpgrade(db);
                }

            } catch (ClassNotFoundException | ClassCastException | IllegalAccessException | InstantiationException e) {

                Log.e(TAG, "Could not migrate from schema from schema: " + i + " to " + i++);
                /* If something fail prevent the DB to be updated to future version if the previous version has not been upgraded successfully */
                break;
            }

        }
    }
}

上面已经做了数据的迁移,国外有个大牛封装的代码摘抄下来:

/**
 * Created by pokawa on 18/05/15.
 */
public class MigrationHelper {

    private static final String CONVERSION_CLASS_NOT_FOUND_EXCEPTION = "MIGRATION HELPER - CLASS DOESN‘T MATCH WITH THE CURRENT PARAMETERS";
    private static MigrationHelper instance;

    public static MigrationHelper getInstance() {
        if(instance == null) {
            instance = new MigrationHelper();
        }
        return instance;
    }

    public void migrate(SQLiteDatabase db, Class<? extends AbstractDao<?, ?>>... daoClasses) {
        generateTempTables(db, daoClasses);
        DaoMaster.dropAllTables(db, true);
        DaoMaster.createAllTables(db, false);
        restoreData(db, daoClasses);
    }

    private void generateTempTables(SQLiteDatabase db, Class<? extends AbstractDao<?, ?>>... daoClasses) {
        for(int i = 0; i < daoClasses.length; i++) {
            DaoConfig daoConfig = new DaoConfig(db, daoClasses[i]);

            String divider = "";
            String tableName = daoConfig.tablename;
            String tempTableName = daoConfig.tablename.concat("_TEMP");
            ArrayList<String> properties = new ArrayList<>();

            StringBuilder createTableStringBuilder = new StringBuilder();

            createTableStringBuilder.append("CREATE TABLE ").append(tempTableName).append(" (");

            for(int j = 0; j < daoConfig.properties.length; j++) {
                String columnName = daoConfig.properties[j].columnName;

                if(getColumns(db, tableName).contains(columnName)) {
                    properties.add(columnName);

                    String type = null;

                    try {
                        type = getTypeByClass(daoConfig.properties[j].type);
                    } catch (Exception exception) {
                        Crashlytics.logException(exception);
                    }

                    createTableStringBuilder.append(divider).append(columnName).append(" ").append(type);

                    if(daoConfig.properties[j].primaryKey) {
                        createTableStringBuilder.append(" PRIMARY KEY");
                    }

                    divider = ",";
                }
            }
            createTableStringBuilder.append(");");

            db.execSQL(createTableStringBuilder.toString());

            StringBuilder insertTableStringBuilder = new StringBuilder();

            insertTableStringBuilder.append("INSERT INTO ").append(tempTableName).append(" (");
            insertTableStringBuilder.append(TextUtils.join(",", properties));
            insertTableStringBuilder.append(") SELECT ");
            insertTableStringBuilder.append(TextUtils.join(",", properties));
            insertTableStringBuilder.append(" FROM ").append(tableName).append(";");

            db.execSQL(insertTableStringBuilder.toString());
        }
    }

    private void restoreData(SQLiteDatabase db, Class<? extends AbstractDao<?, ?>>... daoClasses) {
        for(int i = 0; i < daoClasses.length; i++) {
            DaoConfig daoConfig = new DaoConfig(db, daoClasses[i]);

            String tableName = daoConfig.tablename;
            String tempTableName = daoConfig.tablename.concat("_TEMP");
            ArrayList<String> properties = new ArrayList();

            for (int j = 0; j < daoConfig.properties.length; j++) {
                String columnName = daoConfig.properties[j].columnName;

                if(getColumns(db, tempTableName).contains(columnName)) {
                    properties.add(columnName);
                }
            }

            StringBuilder insertTableStringBuilder = new StringBuilder();

            insertTableStringBuilder.append("INSERT INTO ").append(tableName).append(" (");
            insertTableStringBuilder.append(TextUtils.join(",", properties));
            insertTableStringBuilder.append(") SELECT ");
            insertTableStringBuilder.append(TextUtils.join(",", properties));
            insertTableStringBuilder.append(" FROM ").append(tempTableName).append(";");

            StringBuilder dropTableStringBuilder = new StringBuilder();

            dropTableStringBuilder.append("DROP TABLE ").append(tempTableName);

            db.execSQL(insertTableStringBuilder.toString());
            db.execSQL(dropTableStringBuilder.toString());
        }
    }

    private String getTypeByClass(Class<?> type) throws Exception {
        if(type.equals(String.class)) {
            return "TEXT";
        }
        if(type.equals(Long.class) || type.equals(Integer.class) || type.equals(long.class)) {
            return "INTEGER";
        }
        if(type.equals(Boolean.class)) {
            return "BOOLEAN";
        }

        Exception exception = new Exception(CONVERSION_CLASS_NOT_FOUND_EXCEPTION.concat(" - Class: ").concat(type.toString()));
        Crashlytics.logException(exception);
        throw exception;
    }

    private static List<String> getColumns(SQLiteDatabase db, String tableName) {
        List<String> columns = new ArrayList<>();
        Cursor cursor = null;
        try {
            cursor = db.rawQuery("SELECT * FROM " + tableName + " limit 1", null);
            if (cursor != null) {
                columns = new ArrayList<>(Arrays.asList(cursor.getColumnNames()));
            }
        } catch (Exception e) {
            Log.v(tableName, e.getMessage(), e);
            e.printStackTrace();
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return columns;
    }
}

  

然后在OnUpgrade方法里面去调用

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by migrating all tables data");

        MigrationHelper.getInstance().migrate(db,
                UserDao.class,
                ItemDao.class);
    }

上面代码全是干货,记录下来以备不时之需!

时间: 2024-10-05 05:50:06

GreenDAO数据库版本升级的相关文章

Android SQLite数据库版本升级原理解析

Android使用SQLite数据库保存数据,那数据库版本升级是怎么回事呢,这里说一下. 一.软件v1.0 安装v1.0,假设v1.0版本只有一个account表,这时走继承SQLiteOpenHelper的onCreate,不走onUpgrade. 1.v1.0(直接安装v1.0) 二.软件v2.0 有2种安装软件情况: 1.v1.0   -->  v2.0              不走onCreate,走onUpgrade 2.v2.0(直接安装v2.0)          走onCrea

SQLite数据库版本升级的管理实现

我们知道在SQLiteOpenHelper的构造方法: super(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) 中最后一个参数表示数据库的版本号.当新的版本号大于当前的version时会调用方法: onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 所以我们的重点是在该方法中实现SQLite数据库版本升级的管理

【转】Android使用SQLite数据库版本升级

Android使用SQLite数据库保存数据,那数据库版本升级是怎么回事呢,这里说一下. 一.软件v1.0 安装v1.0,假设v1.0版本只有一个account表,这时走继承SQLiteOpenHelper的onCreate,不走onUpgrade. 1.v1.0(直接安装v1.0) 二.软件v2.0 有2种安装软件情况: 1.v1.0   -->  v2.0              不走onCreate,走onUpgrade 2.v2.0(直接安装v2.0)          走onCrea

浅谈Android数据库版本升级及数据的迁移

概述 Android开发涉及到的数据库采用的是轻量级的SQLite3,而在实际开发中,在存储一些简单的数据,使用SharedPreferences就足够了,只有在存储数据结构稍微复杂的时候,才会使用数据库来存储.而数据库表的设计往往不是一开始就非常完美,可能在应用版本开发迭代中,表的结构也需要调整,这时候就涉及到数据库升级的问题了. 数据库升级 数据库升级,主要有以下这几种情况: 增加表 删除表 修改表 增加表字段 删除表字段 增加表和删除表问题不大,因为它们都没有涉及到数据的迁移问题,增加表只

android数据库版本升级总结

前序: Android版本升级同时Sqlite数据库的升级及之前数据的保留 原理分析: 在android应用程序需要升级时,如果之前的数据库表结构发生了变化或者新添加了表,就需要对数据库进行升级,并保留原来的数据库数据. 程序如何知道数据库需要升级? SQLiteOpenHelper类的构造函数有一个参数是int version,它的意思就是指数据库版本号.比如在软件1.0版本中,我们使用SQLiteOpenHelper访问数据库时,该参数为1,那么数据库版本号1就会写在我们的数据库中. 到了1

《Andorid开源》greenDao 数据库orm框架

一 前言:以前没用框架写Andorid的Sqlite的时候就是用SQLiteDatabase ,SQLiteOpenHelper ,SQL语句等一些东西,特别在写SQL语句来进行 数据库操作的时候是一件很繁琐的事情,有时候没有错误提示的,很难找到错误的地方,即费力又花时间. 现在使用greenDao就可以避免那些繁琐的SQL文了,极大的简化了对Sqlite的操作. greenDao官方网址是:http://greendao-orm.com/ greenDao官方demo下载地址:https://

greenDao数据库框架

1.greendao的引入在project 目录下的build.gradle中添加插件包 dependencies {        classpath 'com.android.tools.build:gradle:2.2.0'        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'        // NOTE: Do not place your application dependencies here; they b

GreenDao数据库框架的配置与增删改查

并非原创,原创地址http://blog.csdn.net/njweiyukun/article/details/51893092 配置---------------------------------- 项目的gradle里的配置 apply plugin: 'org.greenrobot.greendao' buildscript { repositories { mavenCentral() } dependencies { classpath 'org.greenrobot:greend

android GreenDao数据库框架学习(1)

一.GreenDao概述: greenDAO 是一个可以帮助 Android 开发者快速将 Java 对象映射到 SQLite 数据库表单中的 ORM 解决方案.greenDAO的特点运行效率最高.内存消耗最少,官网:http://greendao-orm.com/...github下载地址:https://github.com/greenrobot/greenDAO. 1.  DaoCore:greenDAO的核心库. 2.  DaoExample:greenDAO使用范例项目. 3.  Da