刚开始用的时候知道Gradle里用配置数据库版本的参数,即:
greendao {
schemaVersion 1
daoPackage 'com.tao.greendao.gen'
targetGenDir 'src/main/java'
}
开始以为升级还不容易么,不就是把schemaVersion 抬高一个版本不就ok了吗。但有实际需求的时候就不是这么回事了。
把schemaVersion 变成2的时候,一运行,再查看数据库。要加的字段确实添加进来了。但是以前保存的数据都没有了。这样在保留数据升级的场景中就不适用了。我们要想不删除,首先要了解下GreenDao是怎么做的,那就从代码入手吧。
DaoMaster中的代码:
/** WARNING: Drops all table on Upgrade! Use only during development. */
public static class DevOpenHelper extends OpenHelper {
public DevOpenHelper(Context context, String name) {
super(context, name);
}
public DevOpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory);
}
@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);
}
}
人家早就说啦Use only during development.,都怪自己没看代码。代码中写的很明确,升级的时候是删除所有表,然后再重新创建数据库。
我们应该每次提高数据库版本的时候在表中插入新的字段不就行了吗,于是出现了如下代码:
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < 2) {
db.execSQL(String.format("ALTER TABLE %s ADD %s varchar", 表名, 字段名));
}
if (oldVersion < 3) {
db.execSQL(String.format("ALTER TABLE %s ADD %s integer default 0", 表名,字段名));
}
}
项目上线后,随着数据库的不断升级,onUpgrade中的代码越来越多。时间久了会吐了的。所以要换一种写法,大体思路:
1.首先创建临时表。
2.把当前表的数据插入到临时表中去。
3.删除掉原表,创建新表。
4.把临时表数据插入到新表中去,然后删除临时表。
感觉还是很复杂,就在网上找了下,有人已经写好了:
/**
* 作者:WangJintao
* 时间:2017/4/17
* 邮箱:wangjintao1988@163.com
*/
public class MySqlLiteOpenHelper extends DaoMaster.DevOpenHelper {
public MySqlLiteOpenHelper(Context context, String name) {
super(context, name);
}
public MySqlLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
MigrationHelper.getInstance().migrate(db, StudentDao.class);
}
}
/**
* 作者:WangJintao
* 时间:2017/4/17
* 邮箱:wangjintao1988@163.com
*/
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;
}
private static List<String> getColumns(Database 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;
}
public void migrate(Database db, Class<? extends AbstractDao<?, ?>>... daoClasses) {
generateTempTables(db, daoClasses);
DaoMaster.dropAllTables(db, true);
DaoMaster.createAllTables(db, false);
restoreData(db, daoClasses);
}
private void generateTempTables(Database 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) {
exception.printStackTrace();
}
createTableStringBuilder.append(divider).append(columnName).append(" ").append(type);
if (daoConfig.properties[j].primaryKey) {
createTableStringBuilder.append(" PRIMARY KEY");
}
divider = ",";
}
}
createTableStringBuilder.append(");");
Log.i("lxq", "创建临时表的SQL语句: " + createTableStringBuilder.toString());
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(";");
Log.i("lxq", "在临时表插入数据的SQL语句:" + insertTableStringBuilder.toString());
db.execSQL(insertTableStringBuilder.toString());
}
}
private void restoreData(Database 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();
ArrayList<String> propertiesQuery = 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);
propertiesQuery.add(columnName);
} else {
try {
if (getTypeByClass(daoConfig.properties[j].type).equals("INTEGER")) {
propertiesQuery.add("0 as " + columnName);
properties.add(columnName);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
StringBuilder insertTableStringBuilder = new StringBuilder();
insertTableStringBuilder.append("INSERT INTO ").append(tableName).append(" (");
insertTableStringBuilder.append(TextUtils.join(",", properties));
insertTableStringBuilder.append(") SELECT ");
insertTableStringBuilder.append(TextUtils.join(",", propertiesQuery));
insertTableStringBuilder.append(" FROM ").append(tempTableName).append(";");
StringBuilder dropTableStringBuilder = new StringBuilder();
dropTableStringBuilder.append("DROP TABLE ").append(tempTableName);
Log.i("lxq", "插入正式表的SQL语句:" + insertTableStringBuilder.toString());
Log.i("lxq", "销毁临时表的SQL语句:" + dropTableStringBuilder.toString());
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) || type.equals(int.class)) {
return "INTEGER";
}
if (type.equals(Boolean.class) || type.equals(boolean.class)) {
return "BOOLEAN";
}
Exception exception = new Exception(CONVERSION_CLASS_NOT_FOUND_EXCEPTION.concat(" - Class: ").concat(type.toString()));
exception.printStackTrace();
throw exception;
}
}
MigrationHelper.getInstance().migrate(db, StudentDao.class);
中可以把所有的XXXDao.class都传进去。
修改后的DaoManager变成这样:
/**
* 作者:WangJintao
* 时间:2017/4/17
* 邮箱:wangjintao1988@163.com
*/
public class GreenDaoManager {
private static DaoMaster mDaoMaster;
private static DaoSession mDaoSession;
private static volatile GreenDaoManager mInstance = null;
private static final String DB_NAME = "GreenDao.db";
private GreenDaoManager() {
}
public static void init(Context context) {
MySqlLiteOpenHelper devOpenHelper = new
MySqlLiteOpenHelper(context, DB_NAME);
mDaoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
mDaoSession = mDaoMaster.newSession();
}
public static GreenDaoManager getInstance() {
if (mInstance == null) {
synchronized (GreenDaoManager.class) {
if (mInstance == null) {
mInstance = new GreenDaoManager();
}
}
}
return mInstance;
}
public DaoSession getSession() {
return mDaoSession;
}
}
在Application中初始化:
GreenDaoManager.init(this);
还有个问题没搞出来,希望哪位会的指点一下
某个Entity中有个字段是List<String>该怎么存储呢
网友评论