Sigmund
Sigmund

Reputation: 788

Room Migration?

Shall we describe all fields of a new table while migration from version X to X+1 like it is shown in the doc:

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`))");
}
};

If so, how describe migration for the class with Embedded annotation with nested Embedded annotation?

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 is also Embedded

Upvotes: 0

Views: 1097

Answers (3)

Zohab Ali
Zohab Ali

Reputation: 9574

Another approach using ColumnInfo, then you can directly reference that column

@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)")
  }
}

Upvotes: 0

jaychang0917
jaychang0917

Reputation: 1888

Using @Embedded to annotate a field of an entity / pojo will actually create such subfields in the table.

Room just does you a favor to assemble them to a specific type whenever you do a query having such subfields.

Therefore you should describe all fields of a new table while migration.


Suppose the database has a Foo table for version 1 and you want to add a new table Bar for version 2.

@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)")
  }
}

Upvotes: 3

Martin Zeitler
Martin Zeitler

Reputation: 76679

migrate() should run ALTER TABLE (it's the main purpose, where one does not have to describe whole tables, but only describes the fields or indexes, which shall be altered), as well as occasionally it might contain a CREATE TABLE or a DROP TABLE statement. what you've annotated as @Embedded, that should be another Room entity (this barely influences the migration, but the mapping).

Upvotes: 0

Related Questions