房间迁移?

时间:2018-08-20 16:58:48

标签: android sqlite android-room android-architecture-components

从文档版本XX+1的迁移过程中,我们应描述新表的所有字段吗?

static final Migration MIGRATION_1_2 = new Migration(1, 2) {
@Override
public void migrate(SupportSQLiteDatabase database) {
    database.execSQL("CREATE TABLE `Fruit` (`id` INTEGER, "
            + "`name` TEXT, PRIMARY KEY(`id`))");
}
};

如果是这样,如何用嵌套的migration注释为带有class注释的Embedded来描述Embedded

public class DirectorsStaff {
private String secretKey;
@Embedded
private DirectorsAnswer directorsAnswer;

public String getSecretKey() {
    return secretKey;
}

public void setSecretKey(String secretKey) {
    this.secretKey = secretKey;
}

public DirectorsAnswer getDirectorsAnswer() {
    return directorsAnswer;
}

public void setDirectorsAnswer(DirectorsAnswer directorsAnswer) {
    this.directorsAnswer = directorsAnswer;
}
}

DirectorsStaff也是Embedded

3 个答案:

答案 0 :(得分:0)

migrate()应该运行ALTER TABLE(这是主要目的,不必描述整个表,而仅描述字段或索引(应更改)),偶尔也可以可能包含CREATE TABLEDROP TABLE语句。您注释为@Embedded的对象应该是另一个Room实体(这几乎不会影响迁移,但会影响映射)。

答案 1 :(得分:0)

使用@Embedded注释实体/ pojo 的字段实际上会在表中创建此类子字段。

Room仅在您进行具有此类子字段的查询时帮您将它们组合为特定类型。

因此,您应该在迁移时描述新表的所有字段。


假设数据库具有版本1的Foo表,并且您想为版本2添加新表Bar

@Entity
data class Foo(
  @PrimaryKey val id: Int,
  val name: String
)

@Entity
data class Bar(
  @PrimaryKey val id: Int,
  @Embedded(prefix = "foo_") val foo: Foo
)

class Migration1_2: Migration(1, 2) {
  override fun migrate(database: SupportSQLiteDatabase) {
     database.execSQL("CREATE TABLE Bar (id INTEGER PRIMARY KEY NOT NULL, foo_id INTEGER NOT NULL, foo_name TEXT NOT NULL)")
  }
}

答案 2 :(得分:0)

另一种使用 ColumnInfo 的方法,然后您可以直接引用该列

@Entity
data class Foo(
  @ColumnInfo(name = "foo_id") val id: Int,
  @ColumnInfo(name = "foo_name") val name: String
)

@Entity
data class Bar(
  @PrimaryKey val id: Int,
  @Embedded val foo: Foo
)

class Migration1_2: Migration(1, 2) {
  override fun migrate(database: SupportSQLiteDatabase) {
     database.execSQL("CREATE TABLE Bar (id INTEGER PRIMARY KEY NOT NULL, foo_id INTEGER NOT NULL, foo_name TEXT NOT NULL)")
  }
}
相关问题