GreenDao的更新,不会使数据删除所导致重新创建新表的示例

首先导入依赖
再Projict下的gradle中添加

dependencies {
    classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
}

在Module下的gradle

 在apply plugin: 'com.android.application'下添加apply plugin: 'org.greenrobot.greendao'
然后在
android{
	greendao {
        schemaVersion 1 //版本
        daoPackage '项目的包名.dao' //app包名+生成文件的文件夹名
        targetGenDir 'src/main/java'  //文件生成路径
	}
}
最后添加依赖: implementation 'org.greenrobot:greendao:3.2.2'

创建数据库

public class MyDb {
	    private static MyDb myDb;
	    private final DbBeanDao dbBeanDao;
	
	    public MyDbHelpre() {
	        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(MyApp.getMyApp(), "MySQLite.db");
	        
	        //在这里呢,用来更新的工具类创建好之后,上边创建的可以注释掉,然后使用下边这个
	        MyOpen myOpen = new MyOpen(MyApp.getMyApp(), "MySQLite.db");
        	DaoMaster daoMaster = new DaoMaster(myOpen.getWritableDatabase());
        	只需要改这两行代码就可以进行更新了
	        
	        DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
	        DaoSession daoSession = daoMaster.newSession();
	        dbBeanDao = daoSession.getDbBeanDao();
	    }
	
	    public static MyDbHelpre myDbHelpre() {
	        if (myDbHelpre == null) {
	            synchronized (MyDbHelpre.class) {
	                if (myDbHelpre == null) {
	                    myDbHelpre = new MyDbHelpre();
	                }
	            }
	        }
	        return myDbHelpre;
	    }
	
	    public boolean has(DbBean bean) {
	        List list = dbBeanDao.queryBuilder().where(DbBeanDao.Properties.Name.eq(bean.getName())).list();
	        if (list.size() > 0) {
	            return true;
	        }
	        return false;
	    }

	    //增
	    public void insert(DbBean bean) {
	        if (has(bean)) {
	            return;
	        }
	        dbBeanDao.insert(bean);
	    }

	    //删
	    public void delete(DbBean bean) {
	        dbBeanDao.delete(bean);
	    }

   	 	//改
	    public void update(DbBean dbBean) {
	        dbBeanDao.update(dbBean);
	    }

   		//查
	    public List query() {
	        return dbBeanDao.queryBuilder().list();
	    }
	}

在Activity中初始化数据


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btn_1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        btn_1 = (Button) findViewById(R.id.btn_1);

        btn_1.setOnClickListener(this);

        for (int i = 0; i < 10; i++) {
            DbBean dbBean = new DbBean(null, "张三" + i, "男" + i);
            MyDb.myDb().insert(dbBean);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_1:
                List query = MyDb.myDb().query();
                for (int i = 0; i < query.size(); i++) {
                    Toast.makeText(this, query.toString(), Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}

在实体类中定义

@Entity
public class Bean{
	@Id
	private Long id;	//这里注意,id一定要是Long类型,不能是long
	private String name;
	private String sex;
}
然后在studio中点击Make Project

创建完毕之后,一个简单的数据库就可以运行了
这个工具类的作用是用来创建一个临时表,把旧表的数据存入临时表,当新表创建完成之后,再将临时表中的数据再存入新表,这样就可以保证GreenDao升级不会删除之前的数据
工具类代码:

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(Database db, Class>... daoClasses) {
        generateTempTables(db, daoClasses);
        DaoMaster.dropAllTables(db, true);
        DaoMaster.createAllTables(db, false);
        restoreData(db, daoClasses);
    }

    private void generateTempTables(Database db, Class>... 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 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) {
                        exception.printStackTrace();
                    }

                    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(Database db, Class>... 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 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 getColumns(Database db, String tableName) {
        List 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;
    }
}
public class MyOpen extends DaoMaster.DevOpenHelper {

    public MyOpen(Context context, String name) {
        super(context, name);
    }

    @Override
    public void onUpgrade(Database db, int oldVersion, int newVersion) {
        super.onUpgrade(db, oldVersion, newVersion);
        MigrationHelper.getInstance().migrate(db,DbBeanDao.class);
    }
}

创建好这两个工具类之后,就可以进行数据库的更新了,只需要版本的升级就可以了
以上就是数据库更新版本并且数据不会丢失的步骤了

你可能感兴趣的:(Android)