问题描述
前段时间在公司有项目需要更新版本。在新增的功能需求里,需要对greendao里的Entity实体类新增一个字段。
最开始觉得只需要新增一个对象后,在gradle中修改greendao版本号之后重新build项目即可。
@Entity
public class BibleInspirationDB implements Serializable {
static final long serialVersionUID = -15515456L;
@Id(autoincrement = true)
private Long _id;
private String bibleId; //书籍ID
private String bookName; //书名
private String InspirationContent; //灵感的文本
private String rollTitle;
private String rollIndex; //第几卷
private String secIndex; //第几章
private String partIndex; //第几节 节可以保存多个,用,隔开
private long saveTime;
private String content;
private String netId;
private String testId; //---->需要新增的字段
@Transient //:添加此标记后不会生成数据库表的列
private boolean isSelected;
......
升级greendao版本
greendao {
//指定数据库schema版本号,迁移等操作会用到
schemaVersion 16 // 将上一版本的15修改为16
}
但是在重新运行项目后报错提示没有办法找到新增字段。
原因:
后进过多次排查 发现是在配置greendao版本的时候,将其写在了
android{
....
greendao {
//指定数据库schema版本号,迁移等操作会用到
schemaVersion 16 // 将上一版本的15修改为16
}
}
导致更改版本号之后无法识别
补充:
当发现一些有违正常现象的问题时,且在网上无法相同现象的情况,大多数原因是因为开发过程中一些基础的配置出现问题引起。当往往因为经常配置该设置,所以出现问题的同时不会意识到是最初的原因引起的。这一点望自己在今后开发过程中牢记。
此次学习到的一些额外知识
这次在网上寻找问题时,发现有其他博主提到,在greendao新增字段更新后,会出现原有的旧数据被清除的情况。他们的建议方案是在初始化数据库时,将旧表数据copy到新表中,然后删除旧表。
国外有人开源实现类,亲测可用
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;
}
}
然后自己写一个Helper类,重写onUpgrade方法,在里边实现数据库的数据备份
public class MySqlLiteOpenHelper extends DaoMaster.OpenHelper{
public MySqlLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
super(context, name);
}
@Override
public void onCreate(Database db) {
super.onCreate(db);
/**
* 这个方法
* 1、在第一次打开数据库的时候才会走
* 2、在清除数据之后再次运行-->打开数据库,这个方法会走
* 3、没有清除数据,不会走这个方法
* 4、数据库升级的时候这个方法不会走
*/
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
super.onUpgrade(db, oldVersion, newVersion);
/**
* 1、第一次创建数据库的时候,这个方法不会走
* 2、清除数据后再次运行(相当于第一次创建)这个方法不会走
* 3、数据库已经存在,而且版本升高的时候,这个方法才会调用
*/
if (oldVersion < newVersion) {
MigrationHelper.getInstance().migrate(db, BibleLineAtionDBDao.class);
MigrationHelper.getInstance().migrate(db, BibleInspirationDBDao.class);
}
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
super.onDowngrade(db, oldVersion, newVersion);
/**
* 执行数据库的降级操作
* 1、只有新版本比旧版本低的时候才会执行
* 2、如果不执行降级操作,会抛出异常
*/
}
}
初始化Greendao
public class DBRepository {
public static final String DB_NAME = "data-db";//数据库名称
private static DaoSession mDaoSession;
private static MySqlLiteOpenHelper mySqlLiteOpenHelper;
/**
* 初始化greenDao,这个操作建议在Application初始化的时候添加;
*/
public static void initDatabase(Context context) {
if (context == null) {
throw new IllegalArgumentException("You cannot start a load on a null Context");
}
// DatabaseOpenHelper mHelper = new DaoMaster.DevOpenHelper(context.getApplicationContext(), DB_NAME);
// Database db = mHelper.getWritableDb();
mySqlLiteOpenHelper = new MySqlLiteOpenHelper(context.getApplicationContext(),DB_NAME,null);
Database db = mySqlLiteOpenHelper.getWritableDb();
DaoMaster mDaoMaster = new DaoMaster(db);
mDaoSession = mDaoMaster.newSession();
}
public static DaoSession getDaoSession() {
return mDaoSession;
}
}
在Application中实现初始化
private void initDataBase() {
DBRepository.initDatabase(MyApplication.getContext());
}
网友评论