我正在使用greendao
库进行数据库操作。我有些疑问,
entity
之一中添加任何database table
时,
必须将我的数据库版本更新到下一个版本。如果我不更新
版本应用程序因某种原因崩溃。真的需要在每次添加或更新表实体时更新数据库版本吗?请帮助
提前谢谢
答案 0 :(得分:0)
您必须编写迁移文件以防止擦除数据。
以下是示例代码的外观:
public class DatabaseUpgradeHelper extends DaoMaster.OpenHelper {
public DatabaseUpgradeHelper(Context context, String name) {
super(context, name);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
List<Migration> migrations = getMigrations();
// Only run migrations past the old version
for (Migration migration : migrations) {
if (oldVersion < migration.getVersion()) {
migration.runMigration(db);
}
}
}
private List<Migration> getMigrations() {
List<Migration> migrations = new ArrayList<>();
migrations.add(new MigrationV2());
migrations.add(new MigrationV3());
// Sorting just to be safe, in case other people add migrations in the wrong order.
Comparator<Migration> migrationComparator = new Comparator<Migration>() {
@Override
public int compare(Migration m1, Migration m2) {
return m1.getVersion().compareTo(m2.getVersion());
}
};
Collections.sort(migrations, migrationComparator);
return migrations;
}
private static class MigrationV2 implements Migration {
@Override
public Integer getVersion() {
return 2;
}
@Override
public void runMigration(Database db) {
//Adding new table
UserDao.createTable(db, false);
}
}
private static class MigrationV3 implements Migration {
@Override
public Integer getVersion() {
return 3;
}
@Override
public void runMigration(Database db) {
// Add new column to user table
db.execSQL("ALTER TABLE " + UserDao.TABLENAME + " ADD COLUMN " + UserDao.Properties.Age.columnName + " INTEGER");
}
}
private interface Migration {
Integer getVersion();
void runMigration(Database db);
}
}