如何在没有主键的情况下使用房间从 table 迁移?

How to migrate from table without primary key using room?

我正在尝试迁移到房间,但我的 table 架构是这样的:

CREATE TABLE cache(key text, content text, time integer);

实体:

@Entity(tableName = "cache")
public class Cache{
    public Integer id;
    public String key;
    public String content;
    public Integer time;
}

没有显式声明主键,构建时会发生错误:

An entity must have at least 1 field annotated with @PrimaryKey

我尝试将主键添加到 table,但 sqlite 似乎不支持,有人可以帮助我吗?

摘自此处:http://www.sqlitetutorial.net/sqlite-primary-key/

与其他数据库系统(例如 MySQL、PostgreSQL 等)不同,您不能使用 ALTER TABLE 语句将主键添加到现有的 table。

要解决此问题,您需要:

  • 关闭外键校验
  • 将 table 重命名为另一个 table 名称 (old_table)
  • 创建一个新的 table (table),其结构与您已重命名的 table 完全相同
  • 将数据从 old_table 复制到 table
  • 开启 外键检查

我已经测试了代码,您可以使用迁移规则在现有数据库中添加新列

迁移规则

 static final Migration MIGRATION_1_2 = new Migration(1, 2) {
        @Override
        public void migrate(android.arch.persistence.db.SupportSQLiteDatabase database) {
            database.execSQL("ALTER TABLE cache ADD COLUMN id INTEGER primary KEY AUTOINCREMENT");
        }
    };

将 MigrationRule 添加到 Room 数据库

Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, DATABASE_NAME)
        .addMigrations(MIGRATION_1_2)
        .allowMainThreadQueries()
        .build();

新条目 class 是

@Entity(tableName = "cache")
public class Cache{
    @PrimaryKey(autoGenerate = true)
    public Integer id;
    public String key;
    public String content;
    public Integer time;
}

别忘了 Room 数据库版本是 SQLite db version+1