android - Android Room 迁移未正确处理
问题描述
我已经编写了 Android Room 迁移,但不知何故它不能正确处理它。
这是错误:
Expected:
TableInfo{name='Likes', columns={creatorId=Column{name='creatorId', type='TEXT', notNull=false, primaryKeyPosition=0}, messageId=Column{name='messageId', type='TEXT', notNull=false, primaryKeyPosition=0}, createdAt=Column{name='createdAt', type='TEXT', notNull=false, primaryKeyPosition=0}, id=Column{name='id', type='TEXT', notNull=false, primaryKeyPosition=0}, dbId=Column{name='dbId', type='INTEGER', notNull=true, primaryKeyPosition=1}, timestamp=Column{name='timestamp', type='TEXT', notNull=false, primaryKeyPosition=0}}, foreignKeys=[], indices=[]}
Found:
TableInfo{name='Likes', columns={dbId=Column{name='dbId', type='INTEGER', notNull=true, primaryKeyPosition=1}, creatorId=Column{name='creatorId', type='TEXT', notNull=false, primaryKeyPosition=0}, messageId=Column{name='messageId', type='TEXT', notNull=false, primaryKeyPosition=0}, id=Column{name='id', type='TEXT', notNull=false, primaryKeyPosition=0}, timestamp=Column{name='timestamp', type='TEXT', notNull=false, primaryKeyPosition=0}}, foreignKeys=[], indices=[]}
这是迁移脚本:
database.execSQL("CREATE TABLE Likes (id TEXT, creatorId TEXT, messageId TEXT,"
+ " timestamp TEXT, dbId INTEGER NOT NULL, PRIMARY KEY(dbId))");
这是模型类:
@Entity(tableName = "Likes")
public class LikeDbModel {
@PrimaryKey private int dbId;
private String id;
private String creatorId;
private String messageId;
private String timestamp;
private String createdAt;
public LikeDbModel() {
}
}
任何人都可以帮忙吗?
解决方案
您似乎正在尝试添加 createdAt 列。当您创建数据库时,将 .addMigrations(MIGRATION_1_2) 行添加到数据库的创建中,我认为您已经完成了。
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
YourDatabase.class, "your_database.db")
.addMigrations(
MIGRATION_1_2
)
.build();
然后通过首先删除表然后创建它或使用alter table 语句来正确实施迁移。
static final Migration MIGRATION_1_2 = new Migration(1, 2) {
@Override
public void migrate(SupportSQLiteDatabase db) {
//Either
db.execSQL("drop table Likes"); //if existing table
db.execSQL("CREATE TABLE Likes (id TEXT, creatorId TEXT, messageId TEXT,"
+ " timestamp TEXT, createdAt TEXT, dbId INTEGER NOT NULL, PRIMARY KEY(dbId))")
//or
db.execSQL("alter table add createdAt TEXT");
}
};
您得到的错误是因为房间正在将您的实体与数据库中的现有表进行比较。您还可以将迁移语句包装在 try/catch SQLiteException 中,以查看什么是有效的。
如果您不想丢失表中的数据,请改用 alter table。如果要删除/创建,请确保首先使用新结构将数据复制到新表,将数据复制到新表,删除原始 Likes 表并将新表重命名为 Likes。在此处查看示例
房间文档:https ://developer.android.com/training/data-storage/room/migrating-db-versions
推荐阅读
- c# - SqlDependency - 清理 Started_Outbound 对话
- eclipse - 如何使用 Gradle 构建 Xtext Eclipse 插件?
- python - 在时间序列中查找周期
- mysql - 具有多个条件的 JOINED 表的 SQL 查询
- angular - 发送图像和 JSON 对象 / Angular 的问题
- rest - Gitlab API - 尝试使用私有访问令牌访问 api 时获得 401 未授权
- unit-testing - 如何访问 Vuejs 方法以使用 Jest 进行测试?
- javascript - 使用 puppeteer 永远抓取同一页面
- python - 对相互之间的 2 列进行排序
- php - 如何在用户登录时显示“下载”和“实时预览”按钮,但在用户注销时仅显示“实时预览”按钮?